Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

680. Valid Palindrome II #168

Open
Tcdian opened this issue May 19, 2020 · 1 comment
Open

680. Valid Palindrome II #168

Tcdian opened this issue May 19, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 19, 2020

680. Valid Palindrome II

给定一个非空字符串 s最多 删除一个字符。判断是否能成为回文字符串。

Example 1

Input: "aba"
Output: True

Example 2

Input: "abca"
Output: True
Explanation: You could delete the character 'c'.

Note

  • 字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。
@Tcdian
Copy link
Owner Author

Tcdian commented May 19, 2020

Solution

  • JavaScript Solution
/**
 * @param {string} s
 * @return {boolean}
 */
var validPalindrome = function(s) {
    let chance = 1;
    return isPalindrome(s);
    function isPalindrome(s) {
        let left = 0;
        let right = s.length - 1;
        while (left < right) {
            if (s[left] !== s[right]) {
                if (chance > 0) {
                    chance--;
                    return isPalindrome(s.slice(0, left) + s.slice(left + 1))
                        || isPalindrome(s.slice(0, right) + s.slice(right + 1));
                } else {
                    return false;
                }
            }
            left++;
            right--;
        }
        return true;
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant