Monday, May 11, 2015

Anagrams

来源:Leetcode

原帖:http://oj.leetcode.com/problems/anagrams/

题目:
Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be in lower-case.
Solution: Sort the string to see if they're anagrams.

代码:
 class Solution {  
 public:  
   //Version 1: BST data structure  
   vector<string> anagrams(vector<string> &strs) {  
     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> res;  
     for (auto it : map) {  
       vector<int> &anagrams = it.second;  
       if (anagrams.size() > 1) { // at least more than 1  
         for (auto e : anagrams) {  
           res.push_back(strs[e]);            
         }  
       }  
     }  
     return res;  
   }  
 };  
   
 class Solution {  
 public:  
   //Version 2  
   typedef unordered_map<string, int > MAP; // hash-table  
   vector<string> anagrams(vector<string> &strs) {  
     vector<string> res;  
     MAP anagram;  
     for (int i = 0; i < strs.size(); ++i) {  
       string s = strs[i];  
       sort(s.begin(), s.end());  
       if (!anagram.count(s)) {  
         anagram[s] = i;  
       } else {  
         if (anagram[s] >= 0) {  
           res.push_back(strs[anagram[s]]);  
           anagram[s] = -1;  
         }  
         res.push_back(strs[i]);  
       }  
     }  
     return res;  
   }  
 };  


No comments:

Post a Comment