检查字母字符串是否是C ++中的回文结构

时间:2017-04-18 18:26:33

标签: 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;
    }

目前我收到“Debug Assertion Fail”错误。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

C ++为我们提供了一个内置函数reverse(),该函数可用于反转输入字符串并将其与未反转的字符串进行比较并输出输出。代码如下。

#include<iostream>
#include<algorithm>

using namespace std;

int main(){
    string str; 
    cin>> str;
    
    string rev;
    rev = str;

    reverse(str.begin(), str.end());  // string reverse operation
    
    if(rev == str){
        cout<<"YES"<<endl; // Prints "Yes" if string is palindrome
    }else{
        cout<<"NO"<<endl; // Prints "No" if string is not palindrome
    }

    return 0;
}
相关问题