Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lower-case.
將含有相同的字母可是排序可能不一樣的單詞分類至不一樣的數組面試
這裏利用了String的API方法toCharArray來對兩個單詞是不是相同字母組成的進行比較。可是效率較低。這裏有重複的無效操做,例如得到當前數組的第一個值並從新計算其對應的有序char數組。並且比較兩個char數組的方法形成了三圈循環,帶來的O(n3)的時間複雜度數組
public List<List<String>> groupAnagrams(String[] strs) { List<List<String>> result = new LinkedList<List<String>>(); L1:for(int i = 0 ; i < strs.length ; i++){ String temp = strs[i]; int tempLength = temp.length(); L2:for(int j = 0 ; j<result.size() ; j++){ List<String> currentList = result.get(j); String currentString = currentList.get(0); int currentStringLength = currentString.length(); if(currentStringLength>tempLength){ List<String> newResult = new ArrayList<String>(); newResult.add(temp); result.add(j, newResult); continue L1; }else if (currentStringLength<tempLength){ continue L2; }else{ if(isPermutation(currentString, temp)){ result.get(j).add(temp); continue L1; } } } List<String> newResult = new ArrayList<String>(); newResult.add(temp); result.add(newResult); } return result; } public boolean isPermutation(String s1, String s2){ if(s1.length() != s2.length()){ return false; } char[] s1array = s1.toCharArray(); Arrays.sort(s1array); char[] s2array = s2.toCharArray(); Arrays.sort(s2array); for(int i = 0 ; i<s1array.length ; i++){ if(s1array[i] != s2array[i]){ return false; } } return true; }
其實在這裏利用Map會減小重複的生成char數組的過程。同時使用String.valueof()方法將char數組轉化爲String並利用String的API直接比較兩個字符串是否相等。經過這種方法效率值提升了很多。微信
public List<List<String>> groupAnagrams2(String[] strs){ Map<String, List<String>> map = new HashMap<String, List<String>>(); for(String temp : strs){ char[] current = temp.toCharArray(); Arrays.sort(current); String sortedTemp = String.valueOf(current); if(!map.containsKey(sortedTemp)){ List<String> tempResult = new ArrayList<String>(); tempResult.add(temp); map.put(sortedTemp, tempResult); }else{ map.get(sortedTemp).add(temp); } } return new ArrayList<List<String>>(map.values()); }
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~spa