2015-11-07 87 views
0

我试图解决LeetCode上的this problem。我的解决方案涉及使用基于每个字母的计数的Godel's number的密钥保留散列表,如果我有冲突,我只是遍历数组并比较计数。但是我不知道为什么这个代码不工作:基于范围的C++循环

class Solution { 
    typedef vector<string> vs; 
    const int MAX_ALPHABET = 26; 
    const int MOD = 10007; 
    vector<int> primes; 

    void gen_primes() { 
     primes.push_back(2); 

     for (int i=3; primes.size() < 26; i+=2) { 
      bool isPrime = true; 
      for (int x : primes) 
       if (i % x == 0) { 
        isPrime = false; 
        break; 
       } 
      if (isPrime) 
       primes.push_back(i); 
     } 
    } 

    int compute(vector<int>& v) { 
     int ret = 1; 
     for (int i=0; i<MAX_ALPHABET; i++) { 
      for (int j=0; j<v[i]; j++) 
       ret = (ret * primes[i]) % MOD; 
     } 
     return ret; 
    } 
public: 
    vector<vector<string>> groupAnagrams(vector<string>& strs) { 
     gen_primes(); 

     unordered_map<int, vector< 
      pair< vector<int>, vector<string> > 
     >> hash; 

     for (string s : strs) { 
      vector<int> count(MAX_ALPHABET, 0); 
      for (char c : s) 
       count[c - 'a']++; 
      int key = compute(count); 

      bool inHash = false; 
      // Here is the problem 
      for (auto x : hash[key]) 
       if (x.first == count) { 
        x.second.push_back(s); 
        inHash = true; 
        break; 
       } 
      // Here ends the problem 
      if (!inHash) { 
       hash[key].push_back({count, {s}}); 
      } 
     } 

     vector<vs> ret; 
     for (auto hashGroup : hash) { 
      // hashGroup = {key, vector< pair<vector<int>, vector<string>> >} 
      cout << hashGroup.second[0].second.size() << endl; 
      for (auto anagramGroup: hashGroup.second) { 
       // anagramGroup = pair<vector<int>, vector<string>> 
       sort(anagramGroup.second.begin(), anagramGroup.second.end()); 
       ret.push_back(anagramGroup.second); 
      } 
     } 

     return ret; 
    } 
}; 

但是,如果我有一个正常的替换为范围循环for循环,它的工作原理:

 for (int i=0; i<hash[key].size(); i++) 
      if (hash[key][i].first == count) { 
       hash[key][i].second.push_back(s); 
       inHash = true; 
       break; 
      } 

这种行为是正常的吗?

回答

5

的问题是在这里:

auto x : hash[key] 

这里auto x推断的值,而不是一个参考。所以xvector<pair<vector<int>,vector<string>>>中的元素的副本,不是对它的引用。尝试使用:

auto& x : hash[key] 

问题是不是远程为基础的循环本身,也可以公开相同的“错误”的行为与正常循环:

for (int i=0; i< hash[key].size(); i++) { 
    auto value = hash[key][i]; 
    if (value.first == count) { 
    value.second.push_back(s); 
    inHash = true; 
    break; 
    } 
} 
相关问题