【问题标题】:C++ How to ignore the difference between upper and lower when checking Anagram?C++ 检查 Anagram 时如何忽略上下的区别?
【发布时间】:2018-08-25 02:56:53
【问题描述】:
bool isAnagram(string s1, string s2){
   if(s1.length() != s2.length())
      return false;

  for(int i =0; i <s1.length();i++){
      int pos = (s2.find(s1[i]);
                 if(pos<0)
                 return false;
                 s2.erase(pos,1);

               }
                 return true;

                 return false;

               }

我编写了关于检查 Anagram 的代码,但忽略了忽略上下差异的要求。我对此一无所知。你能帮助我吗?谢谢!

【问题讨论】:

  • 最初我打算将此标记为stackoverflow.com/questions/11635/… 的副本,但这些答案太旧了,这并不好笑。无论如何,我投了反对票,因为这很容易查找,您实际上会花更少的时间在谷歌上搜索“c++ 忽略大小写”

标签: c++ for-loop anagram


【解决方案1】:

在比较之前将两者都转换为小写

std::transform(s1.begin(), s1.end(), s1.begin(), ::tolower);
std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower);

【讨论】:

  • 我需要写一个新函数吗?
【解决方案2】:

简单的方法是将两个字符串都设置为小写(或大写),然后对它们进行排序。如果s1s2互为字谜,那么结果应该是一样的。

【讨论】:

    【解决方案3】:

    您可以使用算法库将大写转换为小写。 在循环之前添加以下行以将其转换为小写。

    #include <algorithm>
    #include <string>
    std::transform(s1.begin(), s1.end(), s1.begin(), ::tolower);
    std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower);
    

    【讨论】:

      【解决方案4】:

      您可以简单地使用 STL algorithm 的强大功能:

      #include <iostream>
      #include <algorithm>
      
      using namespace std;
      
      bool isSameChar(int a, int b)
      {
          return tolower(a) == tolower(b);
      }
      
      bool isAnagram(const string& a, const string& b)
      {
          return a.size() == b.size()
              && is_permutation(a.begin(), a.end(), b.begin(), isSameChar);
      }
      
      int main()
      {
          cout << isAnagram("AbcDE", "ebCda") << endl; // true
          cout << isAnagram("AbcDE", "ebCdaa") << endl; // false
          cout << isAnagram("AbcDE", "ebCde") << endl; // false
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-26
        • 1970-01-01
        • 2020-04-03
        • 1970-01-01
        • 2015-11-19
        相关资源
        最近更新 更多