[leetcode]Anagrams

使用了HashMap和排序,此题就没啥了。在长度一定范围的情况下,用26*的方式做key会更好。

注意两点:

1. java的遍历是for和:  

2. map.keySet()

public class Solution {

    public ArrayList<String> anagrams(String[] strs) {

        ArrayList<String> ans = new ArrayList<String>();

        HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();

        for (int i = 0; i < strs.length; i++)

        {

            char[] chars = strs[i].toCharArray();

            Arrays.sort(chars);

            String key = new String(chars);

            if (map.containsKey(key))

            {

                map.get(key).add(strs[i]);

            }

            else

            {

                ArrayList<String> list = new ArrayList<String>();

                list.add(strs[i]);

                map.put(key, list);

            }

        }

        for (String s : map.keySet())

        {

            if (map.get(s).size() > 1)

            {

                ans.addAll(map.get(s));

            }

        }

        return ans;

    }

}

第二刷,参考了Annie的做法

class Solution {

public:

    vector<string> anagrams(vector<string> &strs) {

        unordered_map<string, vector<int>> map;

        for (int i = 0; i < strs.size(); i++) {

            string s = strs[i];

            sort(s.begin(), s.end());

            map[s].push_back(i);

        }

        vector<string> result;

        for (auto iter = map.begin(); iter != map.end(); iter++) {

            if (iter->second.size() > 1) {

                for (int i = 0; i < iter->second.size(); i++) {

                    result.push_back(strs[iter->second[i]]);

                }

            }

        }

        return result;

    }

};

  

你可能感兴趣的:(LeetCode)