[LeetCode][125. Valid Palindrome] Simple Two Pointers Solution

By Long Luo

This article is the solution Simple Two Pointers Solution of Problem 125. Valid Palindrome.

Very easy, we can use Two Pointers to solve this problem.

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
public boolean isPalindrome(String s) {
if (s == null || s.length() <= 1) {
return true;
}

int n = s.length();
int left = 0;
int right = n - 1;
while (left < right) {
while (left < n && left < right && !(Character.isDigit(s.charAt(left)) || Character.isAlphabetic(s.charAt(left)))) {
left++;
}

while (right > 0 && left < right && !(Character.isDigit(s.charAt(right)) || Character.isAlphabetic(s.charAt(right)))) {
right--;
}

if (Character.toUpperCase(s.charAt(left)) != Character.toUpperCase(s.charAt(right))) {
return false;
}

while (left < right && Character.toUpperCase(s.charAt(left)) == Character.toUpperCase(s.charAt(right))) {
left++;
right--;
}
}

return true;
}

Analysis

  • Time Complexity: \(O(n)\)
  • Space Complexity: \(O(1)\)

All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗