欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Valid Palindrome II

程序员文章站 2024-03-06 21:38:50
...

题目
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.

答案

思路是,设2个指针,left和right,一个指向s的头部,一个指向s的尾部,两个指针逐渐向对方靠拢,靠拢的同时判断s[left]是否不等于s[right], 如果不等于的话,检测is_palindrome(s without s[left]) or is_palindrome(s without s[right]), 如果其一是true,则有可能通过删除一个字符达成palindrome

class Solution {
    public boolean isPal(String s, int omit) {
        int left = 0, right = s.length() - 1;
        while(left <= right) {
            if(left == omit) {
                left++;
                continue;
            }
            if(right == omit) {
                right--;
                continue;
            }
            if(s.charAt(left) != s.charAt(right)) return false;
            left++;
            right--;
        }
        return true;
    }
    public boolean validPalindrome(String s) {
        int left = 0, right = s.length() - 1;

        // Base cases
        if(s.length() <= 1) return true;

        while(left <= right) {
            char c1 = s.charAt(left);
            char c2 = s.charAt(right);
            if(c1 != c2) {
                // Is s a palindrome with s[left] or s[right] removed ?
                return isPal(s, left) || isPal(s, right);
            }
            left++;
            right--;
        }
        return true;
    }
}