Friday, May 17, 2019

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:
  1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
    bool validPalindrome(string s) {
        int l = 0, r = s.size()-1;
        while(l<r)
        {
            if(s[l]!=s[r])
            {
                if(!helper(s, l+1, r) && !helper(s, l, r-1)) return false;
                else return true;
            }
            else
            {
                l++;
                r--;
            }
        }
        return true;
    }
    
    bool helper(string s, int l, int r)
    {
        while(l<r)
        {
            if(s[l++]!=s[r--]) return false;
        }
        return true;
    }
};

No comments:

Post a Comment