筆試題(蘑菇街):迴文串
阿新 • • 發佈:2019-02-16
[程式設計題] 迴文串
給定一個字串,問是否能通過新增一個字母將其變為迴文串。
輸入描述:
一行一個由小寫字母構成的字串,字串長度小於等於10。
輸出描述:
輸出答案(YES\NO).
輸入例子:
coco
輸出例子:
YES做減法,減去任意一個字元,如果是迴文字串,則返回true
#include<iostream> #include<string> using namespace std; bool isPal(string str){ int len = str.length(); for(int i=0; i<len/2; i++) if(str[i] != str[len-1-i]) return false; return true; } bool fun(string str){ if(str.length() <= 2) return true; for(int i=0; i<str.length(); i++) if( isPal( str.substr(0, i) + str.substr(i+1) ) ) return true; return false; } int main(){ string str; while(cin>>str){ cout<<(fun(str) ? "YES" : "NO")<<endl; /*if(fun(str)) cout<<"YES"<<endl; else cout<<"NO"<<endl;*/ } return 0; }