使用C++字谜代码仅在有时有效
Anagram code using C++ only works sometimes
当我比较 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']++;
您的代码仅适用于小写字符 解决方案:在计数之前将每个字符转换为小写。
相关文章:
- GCC对可能有效的代码抛出init list生存期警告
- 这是什么代码?为什么它有效?C++
- 为什么此代码片段有效?如何取消引用空点?
- 使用C++字谜代码仅在有时有效
- 为什么以下代码在在线 ide(gcc 7.2.0) 上有效,但在 ubuntu 上出现错误?
- 为什么第二个代码有效而第一个代码无效?
- 代码是否有效.如果我想显示第一个元素?如果不是,那么 s.begin() 会返回什么?
- 代码 C++ 以添加前缀关键字以使其有效
- 为什么这个简短的模板代码片段有效
- 如何有效地处理Teamcenter ITK C++代码中的错误
- 这是有效的C++代码吗?(在声明范围之外使用本地类型)
- 以有效的方式从 Node .js运行 C 或C++代码
- 使用std ::函数时运行时异常.他们为什么不指向有效的代码
- 为什么认为参考文献在C 底漆第5个中没有变化,以下代码有效
- (C++)比较两段代码,一段有效,一段无效,无法找出区别
- 为什么这段代码在Visual Studio中有效,但在gcc中失败
- 通用lambda,继承和尾随返回类型:此有效代码
- 正在使用 std::time 和 std::srand 有效代码
- 用于确定两个数字中哪个较大的有效代码
- 有效代码无法通过visual studio 2015编译(std函数错误?)