680.Valid Palindrome II

680.Valid Palindrome II

难度:Easy 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.

从头尾开始往内遍历,如果直接遍历完是回文返回true,如果遇到不相等的,将左、右分别删掉一个然后分别检查是否是回文字串,如果是返回true,否则返回 false。 时间复杂度O(n)

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

执行用时 :84 ms, 在所有 C++ 提交中击败了95.29%的用户 内存消耗 :26.1 MB, 在所有 C++ 提交中击败了53.76%的用户

Last updated