HashMap can be a key in another hash map. first map each String to a HashMap that contains character and counts, then put that map in another hash map that contains first hash map and count.
After one loop, take another one, see any String that count Char map in second map's value is larger than 1, add that String to result.
public class Solution {
// Set<String> processed = new HashSet<String>();
// public ArrayList<String> anagrams(String[] strs) {
// if(strs == null || strs.length == 0){
// return new ArrayList<String>();
// }
// ArrayList<String> results = new ArrayList<String>();
// for(int i = strs.length - 1; i > 0; i--){
// if(!processed.contains(strs[i])){
// for(int j = i - 1; j >=0; j--){
// if(!processed.contains(strs[j]) && isAnagram(strs[i], strs[j])) {
// processed.add(strs[j]);
// if(!processed.contains(strs[i])){
// processed.add(strs[i]);
// results.add(strs[i]);
// }
// results.add(strs[j]);
// }
// }
// }
// }
// return results;
// }
// private boolean isAnagram(String inputA, String inputB){
// if(inputA.length() != inputB.length()){
// return false;
// }
// int[] processing = new int[26];
// for(int i = 0; i < inputA.length(); i++){
// processing[inputA.charAt(i) - 97]++;
// processing[inputB.charAt(i) - 97]--;
// }
// for(int j = 0; j < processing.length; j++){
// if(processing[j] != 0){
// return false;
// }
// }
// return true;
// }
public ArrayList<String> anagrams(String[] strs) {
HashMap<String, HashMap<Character, Integer>> strCharsMap
= new HashMap<String, HashMap<Character, Integer>>();
HashMap<HashMap<Character, Integer>, Integer> charsCountMap
= new HashMap<HashMap<Character, Integer>, Integer>();
for(String s : strs) {
HashMap<Character, Integer> map =
new HashMap<Character, Integer>();
for(int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
map.put(c, map.get(c) == null ? 1 : map.get(c)+1);
}
strCharsMap.put(s, map);
charsCountMap.put(map, charsCountMap.get(map) == null ?
1 : charsCountMap.get(map) + 1);
}
ArrayList<String> sol = new ArrayList<String>();
for(String s : strs) {
if(charsCountMap.get(strCharsMap.get(s)) > 1)
sol.add(s);
}
return sol;
}
}
没有评论:
发表评论