[LeetCode] 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:

  1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

判断最多去掉一个字母后回文串是否有效。
aba、abca、abc、acddcb
判断回文串主要是利用双指针(left and right)和递归判断的方法。
题目要求最多去除一个字母。
首先找出回文首末位第一对不匹配的值。
如果left == right,则说明这个字符串是奇数个,如“aba”这种类型。直接返回true。
如果left < right,递归的判断后面的回文情况。并返回true。
如果都不符合以上情况,返回false即可。

class Solution {
public:
    bool validPalindrome(string s) {
        int l = 0, r = s.size() - 1;
        while (l < r && s[l] == s[r]) {
            l++;
            r--;
        }
        if (l == r) {
            return true;
        }
        if (isPalindrome(s, l + 1, r) || isPalindrome(s, l, r - 1)) {
            return true;
        }
        return false;
    }
    bool isPalindrome(string s, int l, int r) {
        while (l < r) {
            if (s[l] == s[r]) {
                l++;
                r--;
            }
            else
            {
                return false;
            }
        }
        return true;
    }
};
// 112 ms

接下来使用直观迭代的方法进行判断

class Solution {
public:
    bool validPalindrome(string s) {
        int left = 0, right = s.size() - 1;
        while (left < right) {
            if (s[left] == s[right]) {
                left++;
                right--;
            }
            else {
                int tmpLeft = left, tmpRight = right - 1;
                while (tmpLeft < tmpRight) {
                    if (s[tmpLeft] != s[tmpRight])
                        break;
                    tmpLeft++;
                    tmpRight--;
                    if (tmpLeft >= tmpRight)
                        return true;
                }
                left++;
                while (left < right) {
                    if (s[left] != s[right])
                        return false;
                    left++;
                    right--;
                }
            }
        }
        return true;
    }
};
// 145 ms

 

posted @ 2017-11-16 10:54  immjc  阅读(124)  评论(0编辑  收藏  举报