使用C++字谜代码仅在有时有效

Anagram code using C++ only works sometimes

本文关键字:有效 代码 C++ 使用      更新时间:2023-10-16

当我比较 Pizza 和 Pizza 或 aaa 和 aaa 等字符串时,我的代码返回 0。当我通过调试器运行代码时,它表明在我的第二个 for 循环中,它实际上是从第一个 for 循环向 arr1 添加元素。我应该如何解决这个问题?

#include <bits/stdc++.h>
using namespace std;
int anagram(string s1,string s2){
int array1[26]={0},array2[26]={0};
//if string lengths are different
if(s1.length()!=s2.length())
return 0; //they are not anagrams
//for string1
for(int i=0;s1[i]!='';i++){
//storing frequency for each letter in the string   
array1[s1[i]-'a']++;     
}
//for string2
for(int i=0;s2[i]!='';i++){
//storing frequency for each letter in the string     
array2[s2[i]-'a']++;   
}
//comparison step
for(int i=0;i<26;i++){
// if any letter has different no of occurence, 
// then strings are not anagrams
if(array1[i]!=array2[i]) 
return 0;
}
return 1;// else they are anagrams
}

数组大小为 26。这意味着它可以容纳 26 件物品。但是,您传递的是包含52个唯一字符的字符串。请记住,大写和小写字母具有不同的 ASCII 值!

因此'P' - 'a'可能不在数组的范围内,因此将是未定义的行为。

您需要确保先将字符转换为小写,即:

array1[tolower(s1[i])-'a']++;

您的代码仅适用于小写字符 解决方案:在计数之前将每个字符转换为小写。