Anagrams
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
思路: anagrams是变化词,string中字符变化,形成新的string。则所有的angrams中字符相同,字符个数相同
所以需要判断是否是anagrams,用排序。mlogm,并且遍历n。
java 代码:
- public List<String> anagrams(String[] strs) {
- List<String> res = new ArrayList<String>();
- int len = strs.length;
- Map<String,Integer> mp = new HashMap<String,Integer>();
- String[] new_strs = new String[len]; len个String的引用
- for(int i=0;i<len;i++) {
- char tmp[] = strs[i].toCharArray();
- Arrays.sort(tmp);
- new_strs[i] = new String(tmp);
- if(mp.containsKey(new_strs[i])) {
- if(mp.get(new_strs[i])>=0) {
- res.add(strs[mp.get(new_strs[i])]); // 处理第一个满足条件的angrams
- mp.put(new_strs[i],-1);
- }
- res.add(strs[i]);
- } else {
- mp.put(new_strs[i],i);
- }
- }
- return res;
- }

浙公网安备 33010602011771号