680. Valid Palindrome II
Problem description:
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: “aba”
Output: True
Example 2:
Input: “abca”
Output: True
Explanation: You could delete the character ‘c’.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
Solution:
Can delete at most one character, implies that the string will not be valid if we delete one character and it does not make a valid palindrome.
- Design a subfunction to check the string is valid or not.
- When we encounter two different characters, we can choose to delete one of them, and check if it’s valid or not.
1 | class Solution: |
1 | class Solution { |
Solution:
Similar idea as above
- remove the character if
s[i]
ands[j]
are different - compare the two strings with their
reversed
string. Note that we only need to compare the rest of string.
1 | class Solution: |
time complexity: $O(n)$
reference: