2012-02-20 31 views
1

我已經實施爲一本書,其是如下的算法:

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; 

}

+1

您是否嘗試使用一些簡單的測試用例在Visual Studio調試器下單步調試?這將是你能做的最具教育意義的事情。 – reuben 2012-02-20 05:19:33

回答

2

即使從彈出的字符串的最後一個字符後,要檢查if(aStack.IsEmpty())將返回true,進而設置inLanguagefalse。因此,即使字符串是迴文,在彈出最後一個字符後仍然將inLanguage設置爲false

1

在pop操作的while循環之前,您沒有重新初始化變量i = 0。

.... 
++i; 

    //match the reverse of w 
    bool inLanguage = true; // assume string is in language 
    while(inLanguage && i < aString.length()) 
    { 
..... 

根據你的代碼在while循環的條件i < aString.length將永遠是假的。

試試這個while循環之前..

i = 0; 
1

你在while循環邏輯是錯誤的,就像納文說。考慮一個$ a的簡單情況會發生什麼:

push 'a' in the stack 
skip $ 
pop 'a' and compare with 'a' -> inLanguage == true 
stack is empty -> inLanguage == false 

這顯然不是你想要的。您需要在循環條件下測試堆棧大小。我會簡化循環到這樣的事情:

while (i < aString.size() && !aStack.isEmpty()) { 
    char stackTop; 
    aStack.pop(stackTop); 
    if(stackTop != aString[i]) break; 
    ++i; 
} 

if (i == aString.size() && aStack.isEmpty()) 
    return true; 
else 
    return false; 
相關問題