Anagram程序调试
Anagram program debugging
我试图调试这个程序,但似乎找不到这个程序的错误。每两个字母的单词都被认为是一个变位词,每一个字母超过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;
}
查找变位符的算法如下::
- 对字符串排序
- 比较字符串
使用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;
}
相关文章:
- 如何在添加文件的情况下在VSCode中调试C++程序
- 如何在 VsCode 上调试 C++/C 程序
- 调试C++程序时遇到问题
- 如何模拟时间的流逝来调试程序?
- 如何在main()之前调试程序崩溃
- 当Visual Studio停止调试程序时会自动清理内存
- VS 代码C++:无法启动调试 - 程序路径丢失或无效
- 如何在 arm 平台中调试 c 程序中的全局变量损坏
- 如何调试 C++ 程序
- 如何使用数组调试C++程序
- 使用Valgrind调试程序-检测分段故障
- 调试程序时奇怪的GDB消息C++
- 使用gdb在MS VC++2010 Express中编译的调试程序
- 调试C程序的断言错误
- CRT参数验证使多线程调试程序崩溃
- 在Linux下捕获SIGKILL的调试程序
- 在c++中调试程序时,我得到一个空白屏幕
- 在GDB中调试程序时如何获取程序的环境
- 尝试调试c++程序在Eclipse Mars上的MAC Pro视网膜与OS X Yosemite版本10.10.5
- 使用容器调试 C++ 程序<set>