Leetcode 49. Group Anagrams & 242. Valid Anagram

来源:互联网 发布:程序员之死 知乎 编辑:程序博客网 时间:2024/05/16 02:14

49. Group Anagrams


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,遍历result,有match放,没match新建放,直接TLE。。

public class Solution { // TLE    public List<List<String>> groupAnagrams(String[] strs) {        List<List<String>> res = new ArrayList<List<String>>();        for(int i = 0; i < strs.length; i++){            boolean find = false;            for(int j = 0; j < res.size(); j++){                if(isAnagram(res.get(j).get(0), strs[i])) { res.get(j).add(strs[i]); find = true; break;}            }            if(find == false){                List<String> newOne = new ArrayList<String>();                newOne.add(strs[i]);                res.add(newOne);                            }        }        return res;    }        private boolean isAnagram(String a, String b){        if(a.length() != b.length()) return false;        int[] table = new int[26];        for(int i = 0; i < a.length(); i++){            table[a.charAt(i) - 'a']++;            table[b.charAt(i) - 'a']--;        }                for(int i = 0; i < 26; i++){            if(table[i] != 0) return false;        }        return true;    }}

看了一下tag,hashtable,哦了。把排序后的单词作为key,如果有这个key,去除对应的value(List<String>类型)放入,没有则加入该key和新的空ArrayList。

public class Solution { // 20ms    public List<List<String>> groupAnagrams(String[] strs) {        if (strs == null || strs.length == 0) return new ArrayList<List<String>>();        Map<String, List<String>> map = new HashMap<String, List<String>>();               for (String s : strs) {            char[] ca = s.toCharArray();            Arrays.sort(ca);            String keyStr = String.valueOf(ca);            if (!map.containsKey(keyStr)) map.put(keyStr, new ArrayList<String>());            map.get(keyStr).add(s);        }        return new ArrayList<List<String>>(map.values());    }}


242. Valid Anagram


Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

思路:

长度不相等,false;然后对比。可以使用数组(提示是lowercase)作hashtable,遍历方式可以是同时加减,最后判断0;也可以是先遍历s,再遍历t,如果过程中得到-1说明不match直接返回。


public boolean isAnagram(String s, String t) {    if (s.length() != t.length()) {        return false;    }    int[] counter = new int[26];    for (int i = 0; i < s.length(); i++) {        counter[s.charAt(i) - 'a']++;        counter[t.charAt(i) - 'a']--;    }    for (int count : counter) {        if (count != 0) {            return false;        }    }    return true;}

public boolean isAnagram(String s, String t) {    if (s.length() != t.length()) {        return false;    }    int[] table = new int[26];    for (int i = 0; i < s.length(); i++) {        table[s.charAt(i) - 'a']++;    }    for (int i = 0; i < t.length(); i++) {        table[t.charAt(i) - 'a']--;        if (table[t.charAt(i) - 'a'] < 0) {            return false;        }    }    return true;}


也可以使用排序:

public boolean isAnagram(String s, String t) {    if (s.length() != t.length()) {        return false;    }    char[] str1 = s.toCharArray();    char[] str2 = t.toCharArray();    Arrays.sort(str1);    Arrays.sort(str2);    return Arrays.equals(str1, str2);}

如果是unicode,如教程所说,直接使用hashtable会比较好些:

Use a hash table instead of a fixed size counter. Imagine allocating a large size array to fit the entire range of unicode characters, which could go up to more than 1 million. A hash table is a more generic solution and could adapt to any range of characters.


0 0