如何快速比较这两个字符串是否相等?
如何快速比较这两个字符串是否相等?两个字符串相等的条件如下,字符串中的每个字母出现的次数都相等。例如:abbcd和acdbb是相等的,因为a都出现1次,b都出现2次,c都出现3次,d都出现4次。请先给出解题的思路,然后用你熟悉的语言进行具体的代码实现。(可在答案中注明解题思路)
// 比较两个字符串字符计数相等 (要越快越好)
bool compare(const char* str1, const char* str2)
{
int len1 = strlen(str1);
int len2 = strlen(str2);
if( len1 != len2 )
return false;
return false;
int len = len1;
int counts[256];
memset(counts, 0, sizeof(counts));
memset(counts, 0, sizeof(counts));
for(int i=0; i<len; i++)
{
counts[str1[i]]++;
counts[str2[i]]--;
}
for(int i=0; i<256; i++)
{
if(counts[i] != 0)
{
return false;
}
}
return true;
}
{
counts[str1[i]]++;
counts[str2[i]]--;
}
for(int i=0; i<256; i++)
{
if(counts[i] != 0)
{
return false;
}
}
return true;
}