LeetCode 680. Valid Palindrome II(双指针)

题意:给定一个字符串,可以最多去掉一个字符,判断是否可以使该字符串成为一个回文串。

分析:head和tail双指针分别指向字符串首尾,如果s[head] != s[tail],则要么去掉s[head],要么去掉s[tail],只需判断s[head + 1]~s[tail]或s[head]~s[tail-1]是否为回文串即可。

class Solution {
public:
    bool judge(string s, int head, int tail){
        while(head <= tail){
            if(s[head] == s[tail]){
                ++head;
                --tail;
            }
            else return false;
        }
        return true;
    }
    bool validPalindrome(string s) {
        if(s == "") return true;
        int head = 0;
        int tail = s.size() - 1;
        while(head <= tail){
            if(s[head] == s[tail]){
                ++head;
                --tail;
            }
            else{
                return judge(s, head + 1, tail) || judge(s, head, tail - 1);
            }
        }
        return true;
    }
};

  

原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12327862.html