leetcode 680. Valid Palindrome II

原文
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

一道不错的题目。题目大意是最多删除一个字母,使得原来的字符串是回文串。
思路:
直接判断当前的字符串是不是回文,如果中间出现s[i]!=s[j],那么进行i+1位和j位字符进行比较,如果s[i+1]和s[j]不等,那么再考虑,i位和j-1位比较。如果s[i+1]和s[j]相等,那么再进行判断剩下的s[i~j]这个字符串,看这个字符串是不是回文,如果是回文,那么继续,否则返回false。
说的有点绕,结合代码会更清楚。

class Solution {
public:
    bool judge(string s, int l, int r) {
        for (int i = l, j = r; i <= j; ++i, --j) {
            if (s[i] != s[j]) {
                return false;
            }
        }
        return true;
    }
    bool validPalindrome(string s) {
        if(s.length()==0||s.length()==1)
            return true;
        int flag=0;
        //以abbab为例
        for(int i=0,j=s.length()-1; i<s.length()/2; i++,j--){
            if(s[i]!=s[j]){ //s[0] != s[4]
                 flag++;
                if(s[i+1]==s[j]) { //s[1] == s[4]
                    if (!judge(s, i+1,j)) { //尝试删掉s[0]也就是a 发现删除a后字符串'bbab'不是回文
                        if (s[i] == s[j-1]) { 
                            if (!judge(s, i, j-1)) {
                                return false;
                            } else {
                                j--;
                            }
                        }
                    }
                    else {
                        i++;
                    }
                }
                else if(s[i]==s[j-1]) {
                    if (!judge(s, i,j-1)) return false;
                    else j--;
                }
                else {
                    return false;
                }
                if(flag>1) {
                    return false;
                }
            }
        }
        return true;
    }
};

原文地址:https://www.cnblogs.com/pk28/p/7862471.html