我正在处理问题集,但我无法弄清楚这个功能是如何工作的。任何帮助将非常感激。主要是我很困惑为什么它使用ASCII与' 0'在他们转向ascii之后,递增和递减的成果是什么呢?它会改变计数吗?
bool isPermutation(string str1, string str2)
{
if(str1.size() != str2.size())
return false;
int i, j, counts[10];
for(i = 0; i < 10;i++)
counts[i] = 0;
for(i = 0; i < str1.size(); i++)
counts[str1[i] - '0']++; // (1)
for(i = 0; i < str1.size(); i++)
counts[str2[i] - '0']--; // (2)
for(i = 0; i < 10; i++) // (3)
if(counts[i] != 0) // (4)
return true; // (5) Should be return false;
return false; // (6) Should be return true;
}
答案 0 :(得分:0)
您发布的代码不正确。最关键的错误是数组counts
太小,就像我在评论中提到的那样。让我稍微更新一下程序:
bool isPermutation(std::string a, std::string b) {
char counts[256] = {0}; // initializes all elements to zero.
if (a.size() != b.size())
return false;
for (int i; i < a.size(); ++i)
counts[a[i]]++;
for (int i; i < b.size(); ++i)
counts[b[i]]--;
for (int i; i < sizeof(counts) / sizeof(counts[0]); ++i)
if (counts[i] != 0)
return false;
return true;
}
整个想法是计算a
中每个角色的实例数;所以当第一个for
- 循环结束时,counts[i]
包含每个字母的实例数(值)(索引,ASCII值)。
然后你在第二个for
循环中递减它。在这些不匹配中,即所有counts
都不为零,那么它就不能是一种排列。