我正在尝试调试此程序,但似乎无法找到此程序的错误。每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;
}
答案 0 :(得分:1)
查找anagram 的算法如下::
使用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)?true:false;
}