【问题标题】:Anagram program debuggingAnagram 程序调试
【发布时间】:2016-07-13 13:50:34
【问题描述】:

我正在尝试调试这个程序,但似乎找不到这个程序的错误。每个 2 个字母的单词被认为是一个字谜,每个超过 2 个字母的单词都被认为不是一个字谜。

#include <string>
#include <iostream>
using namespace std;

// Postcondition: the return value is true if s1 and s2 are anagrams
//   of each other 
bool anagram(string s1, string s2) 
 {
  string temp = s2;
  int i;

  for (i = 0; i < s1.length(); i++);
   {
    // invariant: temp is s2 with first copy of chars 0..i-1 
    //            of s1 removed 
    string newtemp = "";
    bool found = false;

    if (temp.length()==0) 
     {return false;}

    for (int j = 1; j < temp.length(); j++) 
     {
      if (!found && (s1[i] = temp[j])) 
        found = true;
      else 
        newtemp = newtemp + temp[j];
     };

    // assert: newtemp is temp with first occurrence of s1[i] removed
    temp = newtemp;

  };
  return (temp.empty());
}


int main() {
  string str1, str2;

  cout << "Enter two strings: ";
  cin >> str1 >> str2;

  if (anagram(str1,str2))
    cout << "The strings are anagrams!\n";
  else
    cout << "The strings are NOT anagrams.\n";
  return 0;
}

【问题讨论】:

  • 我认为调试器会做得更好!!
  • 只需对字符串进行排序和比较...
  • 在 SO 中搜索 [c++] anagram,您会发现许多对您有帮助的早期问题。

标签: c++ string anagram


【解决方案1】:

找到anagram 的算法如下::

  1. 对字符串进行排序
  2. 比较字符串。

使用 STL C++11,您可以用几行代码实现 bool anagram 函数。

bool anagram (string s1, string s2)
{
      std::sort(s1.begin(), s1.end());
      std::sort(s2.begin(), s2.end());
      return s1 == s2;
}

【讨论】:

  • return s1 == s2;
猜你喜欢
  • 2023-03-22
  • 2016-02-20
  • 2016-01-06
  • 2020-05-21
  • 2020-08-27
  • 2011-06-17
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多