49. 字母異位詞分組——個人認為版
阿新 • • 發佈:2018-12-15
程式碼+註釋+思路:
public class FourNine { public static void main(String[] args) { groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}); } public static List<List<String>> groupAnagrams(String[] strs) { /* 思路: 1. 對字串陣列中每個字串按字元大小進行排序 2. 排序後的字串陣列,如果字串相同證明是異位詞,那麼將排序後的字串作為key, value為HashSet將原字串存到Set中—使用Set的目的是去重,避免有相同的串 3. 遍歷Map中的value,將所有value對應的Set存到結果集合中 注意點:空串與空串算作異位詞 這道題有個問題,就是相同的字串也當作異位詞,個人認為不應該 */ HashMap<String, HashSet> hashMap = new HashMap<>(); for (int i = 0; i < strs.length; i++) { //tmp儲存當前字串,因為後面會對該字串進行排序改變內容 String tmp = xuanZeSort(strs[i]); if (hashMap.containsKey(tmp)) { HashSet set = hashMap.get(tmp); set.add(strs[i]); } else { HashSet set = new HashSet<>(); set.add(strs[i]); hashMap.put(tmp, set); } } List<List<String>> result = new ArrayList<List<String>>(hashMap.keySet().size()); List<HashSet> values=new ArrayList<>(hashMap.values()); for (HashSet value : values ) { //判斷HashSet中是否有包含""的Set,如果有那麼查詢原陣列中所有空串 if (value.contains("")) { List<String> kongChuanList=new ArrayList<>(); for (String s:strs ) { if ("".equals(s)) { kongChuanList.add(""); } } result.add(kongChuanList); }else { result.add(new ArrayList<String>(value)); } } return result; } public static String xuanZeSort(String str) { char[] chs = str.toCharArray(); for (int i = 0; i < chs.length - 1; i++) { for (int j = i + 1; j < chs.length; j++) { if (chs[j] < chs[i]) { char temp = chs[j]; chs[j] = chs[i]; chs[i] = temp; } } } return new String(chs); } }