Saturday, October 5, 2019

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.

class Solution {
public:
    bool validPalindrome(string s) {
        int st = 0, end = s.size() -1;
        while (st < end) {
            if (s[st] == s[end]) {
                st++;
                end--;
            } else {
                return is_palin(s, st + 1, end) || is_palin(s, st, end - 1);
            }
        }
        return true;
    }
   
    bool is_palin(string s, int st, int end) {
        while (st < end) {
            if (s[st] == s[end]) {
                st++;
                end--;
            } else {
                return false;
            }
        }
        return true;
    }
};

No comments:

Post a Comment