LeetCode Minimum Swaps to Group All 1's Together Solution
Given a string
true if the
s can be palindrome after deleting at most one character from it.
s = "aba"
s = "abca"
Explanation: You could delete the character 'c'.
s = "abc"
1 <= s.length <= 105
sconsists of lowercase English letters.
Problem Link: https://leetcode.com/problems/valid-palindrome-ii/
The best approach to solve this problem is using two pointers in opposite directions.
Similar to Valid Palindrome, we will initialize two pointers on the two ends of the string and work our way inside.
We will perform the same palindrome validation by matching the characters at the
If their corresponding characters are different, then we know we must delete one character at one of the
Then, we can check whether the unprocessed substring (excluding the deleted character) is a palindrome.
In Valid Palindrome, we had implemented
is_palindrome with two pointers, here, we are using an iterative approach for two pointers.
The left pointer is
i and the right pointer is
slen - i, where
len(s) - 1.
1def validPalindrome(self, s: str) -> bool: 2 def isPalindrome(s: str): 3 slen = len(s)-1 4 for i in range(slen//2 + 1): 5 if s[i] != s[slen-i]: return False 6 return True 7 8 l, r = 0, len(s)-1 9 while l < r: 10 if s[l] != s[r]: 11 return isPalindrome(s[l+1:r+1]) or isPalindrome(s[l:r]) 12 l += 1 13 r -= 1 14 return True