⬆︎
×

[LC] 0680 Valid Palindrome II

Java

/**
 * <a href="https://leetcode.cn/problems/valid-palindrome-ii/">Valid Palindrome II</a>
 * 贪心;双指针;字符串
 */
class Solution {
    public boolean validPalindrome(String s) {
        int low = 0, high = s.length() - 1;
        while (low < high) {
            if (s.charAt(low) == s.charAt(high)) {
                low++;
                high--;
            } else {
                return checkPalindrome(s, low, high - 1) || checkPalindrome(s, low + 1, high);
            }
        }
        return true;
    }

    private boolean checkPalindrome(String s, int low, int high) {
        for (int i = low, j = high; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
}

Go

func validPalindrome(s string) bool {
    low, high := 0, len(s)-1
    for low < high {
        if s[low] == s[high] {
            low++
            high--
        } else {
            return checkPalindrome(s, low, high-1) || checkPalindrome(s, low+1, high)
        }
    }
    return true
}

func checkPalindrome(s string, low, high int) bool {
    for i, j := low, high; i < j; i, j = i+1, j-1 {
        if s[i] != s[j] {
            return false
        }
    }
    return true
}

JavaScript

/**
 * @param {string} s
 * @return {boolean}
 */
var validPalindrome = function (s) {
    let low = 0, high = s.length - 1;
    while (low < high) {
        if (s[low] === s[high]) {
            low++;
            high--;
        } else {
            return checkPalindrome(s, low, high - 1) || checkPalindrome(s, low + 1, high);
        }
    }
    return true;
};

function checkPalindrome(s, low, high) {
    for (let i = low, j = high; i < j; i++, j--) {
        if (s[i] !== s[j]) {
            return false;
        }
    }
    return true;
}

PHP

class Solution {

    /**
     * @param String $s
     * @return Boolean
     */
    function validPalindrome(string $s): bool {
        $low = 0;
        $high = strlen($s) - 1;
        while ($low < $high) {
            if ($s[$low] == $s[$high]) {
                $low++;
                $high--;
            } else {
                return $this->checkPalindrome($s, $low, $high - 1) || $this->checkPalindrome($s, $low + 1, $high);
            }
        }
        return true;
    }

    private function checkPalindrome(string $s, int $low, int $high): bool {
        for ($i = $low, $j = $high; $i < $j; $i++, $j--) {
            if ($s[$i] != $s[$j]) {
                return false;
            }
        }
        return true;
    }
}

发表评论