Anagram程序调试

Anagram program debugging

本文关键字:调试 程序 Anagram      更新时间:2023-10-16

我试图调试这个程序,但似乎找不到这个程序的错误。每两个字母的单词都被认为是一个变位词,每一个字母超过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;
}

查找变位符的算法如下::

  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;
}