2016年6月16日星期四

[LintCode] #171 Anagrams

Problem: http://www.lintcode.com/en/problem/anagrams/
Solution1 (Dumb version :p):
public class Solution {
    /**
     * @param strs: A list of strings
     * @return: A list of strings
     */
    public List<String> anagrams(String[] strs) {
        List<String> result = new ArrayList<String>();
        boolean[] selected = new boolean[strs.length]; 
        for (int i = 0; i < selected.length; i++) {
            selected[i] = false;
        }
        for (int i = 0; i < strs.length; i++) {
            for (int j = i + 1; j < strs.length; j++) {
                String s1 = strs[i];
                String s2 = strs[j];
                
                if (s1.length() != s2.length())
                {
                    continue;
                }
                
                HashMap<Character, Integer> map1 = new HashMap<Character, Integer>();
                HashMap<Character, Integer> map2 = new HashMap<Character, Integer>();
                
                for (char c : s1.toCharArray()) {
                    map1.put(c, map1.containsKey(c) ? map1.get(c) + 1 : 1);
                }
                
                for (char c : s2.toCharArray()) {
                    map2.put(c, map2.containsKey(c) ? map2.get(c) + 1 : 1);
                }
                
                if (map1.equals(map2)) {
                    if (!selected[i]) {
                        result.add(s1);
                        selected[i] = true;
                    }
                    if (!selected[j]) {
                        result.add(s2);
                        selected[j] = true;
                    }
                }
            }
        }
        return result;
    }
}

Solution2 (Hashing :p): http://www.jiuzhang.com/solutions/anagrams/
Q: How to figure out the correct a and b to use in Hashing function? How to prevent collision?

Homework:
Read Terry's lecture note on hashing and hash table :p

没有评论:

发表评论