[LeetCode][680. Valid Palindrome II] 3 Approaches: Brute Force, Recursion and Two Pointers
By Long Luo
This article is the solution 3 Approaches: Brute Force, Recursion and Two Pointers of Problem 680. Valid Palindrome II.
Here shows 3 Approaches to slove this problem: Brue Force, Recursion and Two Pointers.
Brue Force
Let’s start from the simplest method:
- if \(len(str) \le 2\), definitely return \(\textit{true}\);
- if the string is a palindrome, return \(\textit{true}\);
- if not, enumerate each position as the deleted position, and then check the remaining strings is it a palindrome.
Time complexity of this approach is \(O(n^2)\), time limit will be exceeded.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32public static boolean validPalindrome_bf(String s) {
int len = s.length();
if (len <= 2 || validPalindrome(s, 0, len - 1)) {
return true;
}
for (int i = 0; i < len; i++) {
String str = s.substring(0, i) + s.substring(i + 1, len);
if (validPalindrome(str, 0, str.length() - 1)) {
return true;
}
}
return false;
}
public static boolean validPalindrome(String s, int left, int right) {
int len = s.length();
if (left >= len || right < 0 || left > right) {
return false;
}
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
Analysis
- Time Complexity: \(O(n^2)\)
- Space Complexity: \(O(1)\)