2017-06-13 33 views
0

我已經寫了一個代碼來檢查字符串是否是迴文,它應該排除空格和特殊字符,並且應該不區分大小寫。所以函數isPalindrome(string A)接受一個字符串,如果它的迴文返回1,否則返回0。迴文排除特殊字符和空格

例如:輸入:一個人,一個計劃,運河:巴拿馬 輸出:1 下面是代碼 -

int isPalindrome(string A) { 
    string::iterator it; 
    string::reverse_iterator rit; 
    it=A.begin(); 
    rit=A.rbegin(); 
    while(it!=A.end() && rit!=A.rend()){ 
     while(!isalnum(*rit))  //if char from the end is not alphanumeric, then increment the reverse iterator till we find the alphanumeric char. 
      ++rit; 
     while(!isalnum(*it))  //if char from the start is not alphanumeric, then increment the iterator till we find the alphanumeric char. 
      ++it; 
     if(tolower(*it)!=tolower(*rit)) //case in-sensitive comparison 
      return 0; 
     ++it; 
     ++rit; 
    } 
    return 1; 
} 

它非常適用輸入的像A man, a plan, a canal: Panama""A man, a plan, a canal: Panama但所有的變型當我輸入"A man, a plan, a canal: Panama"時,它會因運行時錯誤而失敗。

所以請讓我知道我哪裏錯了?

+3

這聽起來像你可能需要學習如何使用調試器來逐步通過你的代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:[如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – NathanOliver

+0

你忘了檢查內部' while'。如前所述,你不能沒有調試器開發。 – Boiethios

回答

0

問題是這兩個迭代器可能已經在嵌套while循環中結束了,應該檢查這個。

int isPalindrome(string A) { 
    string::iterator it; 
    string::reverse_iterator rit; 
    it=A.begin(); 
    rit=A.rbegin(); 
    while(it!=A.end() && rit!=A.rend()){ 
     while(rit != A.rend() && !isalnum(*rit))  //if char from the end is not alphanumeric, then increment the reverse iterator till we find the alphanumeric char. 
      ++rit; 
     while(it != A.end() && !isalnum(*it))  //if char from the start is not alphanumeric, then increment the iterator till we find the alphanumeric char. 
      ++it; 

     if (it == A.end() || rit == A.rend()) 
      break; 

     if(tolower(*it)!=tolower(*rit)) //case in-sensitive comparison 
      return 0; 
     ++it; 
     ++rit; 
    } 
    return 1; 
} 
+2

你至少應該解釋什麼是錯誤的以及你修正了什麼,而不是提供裸露的代碼。 – Slava

相關問題