[蘑菇街]回文串

题目描述

给定一个字符串,问是否能通过添加一个字母将其变为回文串。

输入描述:
一行一个由小写字母构成的字符串,字符串长度小于等于10。


输出描述:
输出答案(YES\NO).

输入例子:
coco

输出例子:
YES
思路一:暴力,超级暴力。。。O(n2),因为题目说了字符串的长度不会超过10,也没想起其他方法,所以直接暴力写了一下。。。

#include<iostream>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
bool isPlalindrome(string s){
    string s1=s;
    reverse(s1.begin(),s1.end());
    if(s1==s)
        return true;
    else
        return false;
}
int main(){
    string s;
    while(cin>>s){
        map<char,int> tab;
        bool flag=0;
        for(int i=0;i<s.size();i++){
            if(tab[s[i]]==0){
                tab[s[i]]++;   
                string s1=s;
                string::iterator itr=s1.begin();
                for(;itr<=s1.end();++itr){
                    s1.insert(itr,1,s[i]);
                    if(isPlalindrome(s1)){
                        cout<<"YES"<<endl;
                        flag=1;
                        break;
                    }
                    s1=s;
                }
            }
            if(flag==1)
                break;
        }
        if(flag==0)
            cout<<"NO"<<endl;
    }
}


思路二:添加一个字符成为回文串相当于删掉一个字符是回文串,双指针从两边扫描,遇到不相等的,有两种选择,删掉前面的和删掉后面的,所以遍历两遍。用O(n)的复杂度就可以解决

#include<iostream>
#include<string>
using namespace std;
bool isPlalindrome(string s){
    int i=0,j=s.size()-1;
    while(i<=j&&s[i]==s[j]){
        i++;
        j--;
    }
    if(i>j)
        return true;
    else
        return false;
}
int main(){
    string s;
    while(cin>>s){
        int i=0,j=s.size()-1;
        int cnt1=0,cnt2=0;
        while(i<=j){
            if(s[i]!=s[j]){
                i++;
                cnt1++;
            }
            else{
                i++;
                j--; 
            }  
        }
        i=0,j=s.size()-1;
        while(i<=j){
            if(s[i]!=s[j]){
                j--;
                cnt2++;
            }
            else{
                i++;
                j--; 
            }  
        }
        if(cnt1==1||cnt2==1)
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
    }
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值