-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidPalindrome2.java
More file actions
37 lines (34 loc) · 943 Bytes
/
ValidPalindrome2.java
File metadata and controls
37 lines (34 loc) · 943 Bytes
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
32
33
34
35
36
37
package string;
/**
* @author Shogo Akiyama
* Solved on 05/08/2020
*
* 125. Valid Palindrome
* https://leetcode.com/problems/valid-palindrome/
* Difficulty: Easy
*
* Approach: Two Pointers & Iteration (Optimized)
* Runtime: 2 ms, faster than 97.57% of Java online submissions for Valid Palindrome.
* Memory Usage: 39.2 MB, less than 29.46% of Java online submissions for Valid Palindrome.
*
* Time Complexity: O(n)
* Space Complexity: O(1)
* Where n is the length of the string
*
* @see StringTest#testValidPalindrome()
*/
public class ValidPalindrome2 {
public boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
while (!Character.isLetterOrDigit(s.charAt(i)) && i < j)
i++;
while (!Character.isLetterOrDigit(s.charAt(j)) && i < j)
j--;
if (Character.toLowerCase(s.charAt(i++)) != Character.toLowerCase(s.charAt(j--)))
return false;
}
return true;
}
}