我有一个anagram函数,它的工作方式与我想要的不一样。
例如,将正确地工作,以便函数返回1:
is_anagram("a bc", "Cab")is_anagram("a12+-", "1a2")但是函数不正确地返回1,用于:
is_anagram("1a3", "1a +=")守则是:
#include <ctype.h>
#include <stdio.h>
int is_anagram(char *s1, char *s2) {
// 2 Empty Num Arrays
int s1_count[99] = {0};
int s2_count[99] = {0};
int c = 0;
while (s1[c] != '\0')
{
if (isupper(s1[c]))
{
s1_count[tolower(s1[c]) - 'a']++;
}
else
{
s1_count[s1[c] - 'a']++;
}
c++;
}
c = 0;
while (s2[c] != '\0')
{
if (isupper(s2[c]))
{
s2_count[tolower(s2[c]) - 'a']++;
}
else
{
s2_count[s2[c] - 'a']++;
}
c++;
}
for (int i = 0; i < 26; i++)
{
if (s1_count[i] != s2_count[i])
{
return 0;
}
}
return 1;
}
int main(void)
{
printf("%d\n", is_anagram("a bc", "Cab")); // expected to print 1
printf("%d\n", is_anagram("a12+-", "1a2")); // expected to print 1
printf("%d\n", is_anagram("1a3", "1a +=")); // expected to print 0
return 0;
}发布于 2022-07-26 10:01:43
如果希望s1和s2包含非字母字符(如示例中所示),则需要更改以下几点:
数组。
。
顺便说一句,您不需要isupper()的支票。您只需对每个字符调用tolower()即可。如果它不是大写字母,它将返回未经修改的字符。
https://stackoverflow.com/questions/73121024
复制相似问题