680. Valid Palindrome II
Asked at 16Meta96Amazon44Google38Microsoft36Bloomberg30Apple22Yandex84Whatnot100Fortinet89Roku87Attentive59eBay53IBM50Visa39TikTok35Uber22
Problem
Decide whether s can become a palindrome after deleting at most one character.
Example: "abca" → true (delete c); "abc" → false
Constraints: length ≤ 10⁵.
Walk inward; at the first mismatch you may delete one char: check whether s[l+1..r] or s[l..r-1] is a palindrome.
Complexity: O(n).
class Solution:
def validPalindrome(self, s: str) -> bool:
def pal(l, r):
while l < r:
if s[l] != s[r]:
return False
l, r = l + 1, r - 1
return True
l, r = 0, len(s) - 1
while l < r:
if s[l] != s[r]:
return pal(l + 1, r) or pal(l, r - 1)
l, r = l + 1, r - 1
return True
assert Solution().validPalindrome("aba") is True
assert Solution().validPalindrome("abca") is True
assert Solution().validPalindrome("abc") is False
class Solution {
public boolean validPalindrome(String s) {
for (int l = 0, r = s.length() - 1; l < r; l++, r--)
if (s.charAt(l) != s.charAt(r)) return pal(s, l + 1, r) || pal(s, l, r - 1);
return true;
}
private boolean pal(String s, int l, int r) {
while (l < r) if (s.charAt(l++) != s.charAt(r--)) return false;
return true;
}
}
func validPalindrome(s string) bool {
pal := func(l, r int) bool {
for ; l < r; l, r = l+1, r-1 {
if s[l] != s[r] {
return false
}
}
return true
}
for l, r := 0, len(s)-1; l < r; l, r = l+1, r-1 {
if s[l] != s[r] { // delete one of the two
return pal(l+1, r) || pal(l, r-1)
}
}
return true
}