标签:instead 代码 ati 更新 min 需求 rev abs ima
实现1:
class Solution { public List<String> wordsAbbreviation(List<String> dict) { if (dict == null || dict.size() == 0) { return new ArrayList<String>(); } int[] prefix = new int[dict.size()]; String[] result = new String[dict.size()]; Map<String, Integer> count = new HashMap<>(); // initialization for (int i = 0; i < dict.size(); i++) { prefix[i]++; String abbr = abbreviate(dict.get(i), prefix[i]); result[i] = abbr; count.put(abbr, count.getOrDefault(abbr, 0) + 1); } boolean hasDup = true; while (hasDup) { hasDup = false; for (int i = 0; i < dict.size(); i++) { if (count.get(result[i]) > 1) { hasDup = true; prefix[i]++; String newAbbr = abbreviate(dict.get(i), prefix[i]); result[i] = newAbbr; count.put(newAbbr, count.getOrDefault(newAbbr, 0) + 1); } } } // P3: 生成List List<String> resultList = new ArrayList<>(); Collections.addAll(resultList, result); return resultList; } private String abbreviate(String s, int prefix) { if (s.length() - prefix - 1 <= 1) { return s; } else { // P2: 注意题意不是每次均匀往中间缩两格,只是prefix缩一格进去。 return s.substring(0, prefix) + (s.length() - prefix - 1) + s.substring(s.length() - 1, s.length()); } } }
实现2:
class Solution { public List<String> wordsAbbreviation(List<String> dict) { if (dict == null || dict.size() == 0) { return new ArrayList<String>(); } Map<String, List<Integer>> strIdxes = new HashMap<>(); int prefix = 1; // initialization for (int i = 0; i < dict.size(); i++) { String abbreved = abbreviate(dict.get(i), prefix); strIdxes.putIfAbsent(abbreved, new ArrayList<>()); strIdxes.get(abbreved).add(i); } while (strIdxes.size() < dict.size()) { prefix++; System.out.println(prefix); // P1: 每次要开新map的原因: 你不能在遍历keySet()的时候又给keySet()插入删除key值,这是逻辑不对而且编译会报错ConcurrentModificationException。 Map<String, List<Integer>> newMap = new HashMap<>(); for (String s : strIdxes.keySet()) { List<Integer> indexes = strIdxes.get(s); if (indexes.size() == 1) { newMap.put(s, indexes); continue; } for (int index : indexes) { String newAbbreved = abbreviate(dict.get(index), prefix); newMap.putIfAbsent(newAbbreved, new ArrayList<>()); newMap.get(newAbbreved).add(index); } } strIdxes = newMap; } // P3: 生成List String[] resultArr = new String[dict.size()]; for (String s : strIdxes.keySet()) { resultArr[strIdxes.get(s).get(0)] = s; } List<String> result = new ArrayList<>(); Collections.addAll(result, resultArr); return result; } private String abbreviate(String s, int prefix) { if (s.length() - prefix - 1 <= 1) { return s; } else { // P2: 注意题意不是每次均匀往中间缩两格,只是prefix缩一格进去。 return s.substring(0, prefix) + (s.length() - prefix - 1) + s.substring(s.length() - 1, s.length()); } } }
leetcode527 - Word Abbreviation - hard
标签:instead 代码 ati 更新 min 需求 rev abs ima
原文地址:https://www.cnblogs.com/jasminemzy/p/9612919.html