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