`

LeetCode 49 - Anagrams

 
阅读更多

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

 

public List<String> anagrams(String[] strs) {
    List<String> result = new ArrayList<>();
    Map<String, List<String>> map = new HashMap<>();
    if(strs == null || strs.length==0) return result;
    for(String str:strs) {
        char[] seq = str.toCharArray();
        Arrays.sort(seq);
        String key = new String(seq);
        if(map.containsKey(key)) {
            map.get(key).add(str);
        } else {
            List<String> list = new ArrayList<>();
            list.add(str);
            map.put(key, list);
        }
    }
    for(List<String> list:map.values()) {
        if(list.size()>1)
            result.addAll(list);
    }
    return result;
}

 

C++版本:

vector<string> anagrams(vector<string>& strs) {
    vector<string> result;
    unordered_map<string, vector<string>> map;
    for(auto& str : strs) {
        string s(str);
        sort(s.begin(), s.end());
        map[s].push_back(str);
    }
    for(auto& p : map) {
        if(p.second.size() > 1) 
            result.insert(result.end(), p.second.begin(), p.second.end());
    }
    return result;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics