680. Valid Palindrome II

来源:互联网 发布:翻唱粤语的网络女歌手 编辑:程序博客网 时间:2024/06/05 09:31

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: TrueExplanation: 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.

题目大意是,在允许删除一个字符的前提下,判断一个字符串是否可能是回文字符串。

eg:

a b b c d c b a

0 1 2 3 4 5 6 7

设置两根指针,left 和right 分别指向头尾。 

当left == 2 && right == 5 的时候,他们指向的字符不一样,可以被分为两种情况:

1. 删除s[left],判断s[3] - s[5]是不是回文

2. 删除s[right], 判断s[2] - s[4]是不是回文

根据上述推断可以写出代码:

class Solution {public:    bool isPalindrome(string s, int left, int right) {        while (left < right) {            if (s[left] == s[right]) {                left++;                right--;            } else {                return false;            }        }        return true;    }    bool validPalindrome(string s) {        if (s.length() < 2) {            return true;        }        int left = 0;        int right = s.length() - 1;        while (left < right) {            if (s[left] != s[right]) {                return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);            }                 left++;                right--;                    }        return true;    }};