2017-04-18 4 views
-1

文字列が回文かどうかをチェックするコードを書こうとしました。コードは次のとおりです。アルファベット文字列がC++の回文体であるかどうかを調べる

#include <iostream> 
#include <string> 
using namespace std; 

bool pal(string str)//This block of code checks if input string is a palindrome 
{ 
bool valid; 
int i; 
for (i = 0; i < str.length(); i++) 
{ 
    if (str[-i] == str[i]) 
    { 
     valid = true; 
    } 
    else 
    { 
     valid = false; 
    } 
} 
return valid; 
} 

int main() 
{ 
string s; 
cin >> s; 

if (!pal(s)) 
{ 
    cout << "NO" << endl; 
} 
else 
{ 
    cout << "YES" << endl; 
} 
return 0; 
    } 

現在、「デバッグアサーション失敗」エラーが発生しています。

+1

str [-i]はC++では動作しません。Pythonから借用したと思いますか? str [str.size()-1-i] – AlexG

+0

'i'が1になるとき' str [-i] 'とは何ですか? – NathanOliver

+0

インターネットを "stackoverflow C++ palindrome alphabet"で検索することを強くお勧めします。 –

答えて

1
str[-i] == str[i] 

は、負のインデックスがC++で有効なインデックスではないため、問題です。

戦略を少し変更する必要があります。

bool pal(string str) 
{ 
    int i = 0; 
    int j = str.length() - 1; 

    for (; i < j; ++i, --j) 
    { 
     if (str[i] != str[j]) 
     { 
     // No need for any more checks. 
     return false; 
     } 
    } 

    // If we come here, the string is a palindrome.  
    return true; 
} 
+0

ありがとう!それも同様に動作するようです。私はそれを見て2番目に、私は間違っていたものを解決することができます。 – Yar

+0

if(str [str.size()-1-i] == str [i])。それは私の今のところだが、とにかく感謝している。 – Yar

+0

_negative indicesはC++の有効なインデックスではない_技術的には、そうである。しかし、OPが望む方法ではありません。例:http://ideone.com/5gWNMK –

関連する問題