Java教程

PO91回文字符串

本文主要是介绍PO91回文字符串,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

image

思路:和判断回文字符串差不多,双指针法

#include <string>
using namespace std;

class Solution
{
public:
    bool validPalindrome(string s)
    {
        return verify(s, 0, s.length() - 1, 0);
    }

    bool verify(string s, int i, int j, int diffcnt)
    {
        while (i < j)
        {
            if (s[i] == s[j])
            {
                i++;
                j--;
            }
            else
            {
                diffcnt++;
                if (diffcnt > 1)
                {
                    return false;
                }

                return verify(s, i + 1, j, diffcnt) || verify(s, i, j - 1, diffcnt);
            }
        }

        return true;
    }
};

int main(){
    Solution solution;
    string str;
    cin>>str;
    if(solution.validPalindrome(str)){
        cout<<"true"<<endl;
    }else{
        cout<<"false"<<endl;
    }
    return 0;
}

-[1]

这篇关于PO91回文字符串的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!