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

Valid Palindrome II

程序员文章站 2024-03-06 23:37:08
...

http://www.lintcode.com/zh-cn/problem/valid-palindrome-ii/

public class Solution {
    /**
     * @param s: a string
     * @return: nothing
     */
    public boolean validPalindrome(String s) {
        // Write your code here
        int left = 0;
        int right = s.length() - 1;
        boolean hasDeal = false;
        while (left < right) {
            if (s.charAt(left) == s.charAt(right)) {
                left++;
                right--;
                continue;
            } else {
                if (!hasDeal) {
                    if (s.charAt(left + 1) == s.charAt(right)) {
                        left += 2;
                        right--;
                        hasDeal = true;
                    } else if (s.charAt(left) == s.charAt(right - 1)) {
                        left++;
                        right -= 2;
                        hasDeal = true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }

            }
        }
        return true;
    }
}