Отладка программы Anagram

Я пытаюсь отладить эту программу, но не могу найти ошибку с этой программой. Каждое двухбуквенное слово считается анаграммой, а каждое слово, содержащее более двух букв, не является анаграммой.

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

-3

Решение

Алгоритм поиска анаграмма как следует ::

  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)?true:false;
}
1

Другие решения

Других решений пока нет …