繁体   English   中英

使用 C++ 的 Anagram 代码有时仅适用

[英]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]!='\0';i++){
  //storing frequency for each letter in the string   
   array1[s1[i]-'a']++;     
  }

 //for string2
  for(int i=0;s2[i]!='\0';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']++;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM