我试图在LeetCode上解决this problem。我的解决方案涉及从每个字母的计数中保留一个基于Godel's number的密钥的哈希映射,如果我有冲突,我只是迭代一个数组并比较计数。但是我不知道为什么这段代码不起作用:
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 normal for for替换for range循环,它就可以工作:
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;
}
这种行为是否正常?
答案 0 :(得分:5)
问题在于:
$scope.$watch
此处auto x : hash[key]
推断的是值,而不是参考。所以auto x
是x
中元素的副本,而不是对它的引用。试试:
vector<pair<vector<int>,vector<string>>>
问题不在于基于范围的循环本身,您可以使用正常循环暴露相同的“错误”行为:
auto& x : hash[key]