我已經實施爲一本書,其是如下的算法:
L = {瓦特$ W ':w是大於$瓦特字符的可能爲空字符串'=反向(W)}
繼僞代碼之後,我爲我的程序編寫了代碼,它將輸入一個字符串,例如(A $ A,ABC $ CBA),並比較$之前和之後的字符以確定它們是否是迴文。我完全按照本書的指示編寫代碼,但該程序無法正常工作。無論我輸入什麼,它總是返回錯誤。
我不知道我在做什麼錯。
這裏是我寫的代碼:
#include <iostream>
#include "stack.h"
#include <string>
using namespace std;
bool isInLanguage(string aString)
{
Stack<char> aStack;
int i = 0;
// ch is aString[i]
while(aString[i] != '$')
{
aStack.push(aString[i]);
++i;
}
//skip the $
++i;
//match the reverse of w
bool inLanguage = true; // assume string is in language
while(inLanguage && i < aString.length())
{
char stackTop;
aStack.pop(stackTop);
if(stackTop == aString[i])
++i; //characters match
else
//top of stack is not aString[i]
inLanguage = false; //reject string
if(aStack.isEmpty())
{
//pop failed, stack is empty. first half of string
//is shorter than second half)
inLanguage = false;
} // end if
} // end while
if (inLanguage && aStack.isEmpty())
return true;
else
return false;
} // end isInLanguage
int main()
{
string str;
bool boolean;
cout << "Enter a string to be checked by the algorithm : ";
cin >> str;
boolean = isInLanguage(str);
if (boolean == true)
cout << "The string is in language.\n";
else
cout << "The string is not in language.\n";
return 0;
}
您是否嘗試使用一些簡單的測試用例在Visual Studio調試器下單步調試?這將是你能做的最具教育意義的事情。 – reuben 2012-02-20 05:19:33