Accepted 44ms c++ solution use a std::unordered_map to record the word.


  • 0
    class Solution {
    public:
        std::vector<std::string> anagrams(std::vector<std::string>& strs) {
            std::vector<std::string> res;
    		std::unordered_map<std::string, int> hmap;
    		for (int i = 0; i != strs.size(); ++i) {
    			std::string s = strs[i];
    			std::sort(s.begin(), s.end());
    			auto iter = hmap.find(s);
    			if (iter != hmap.end()) {
    				if (iter->second != -1) {
    					res.push_back(strs[iter->second]);
    					iter->second = -1;
    				}
    				res.push_back(strs[i]);
    			}
    			else
    				hmap[s] = i;
    		}
    		return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.