File tree Expand file tree Collapse file tree 1 file changed +29
-5
lines changed Expand file tree Collapse file tree 1 file changed +29
-5
lines changed Original file line number Diff line number Diff line change 2
2
* <a href="https://leetcode.com/problems/valid-palindrome/">week03-1.valid-palindrome</a>
3
3
* <li>Description: return true if it is a palindrome </li>
4
4
* <li>Topics: Two Pointers, String </li>
5
- * <li>Time Complexity: O(N), Runtime 13ms </li>
6
- * <li>Space Complexity: O(N ), Memory 45.55MB </li>
5
+ * <li>Time Complexity: O(N), Runtime 2ms </li>
6
+ * <li>Space Complexity: O(1 ), Memory 42.75MB </li>
7
7
*/
8
8
class Solution {
9
9
public boolean isPalindrome (String s ) {
10
- String str = s .toLowerCase ().replaceAll ("[^0-9a-z]" , "" );
10
+ int left = 0 ;
11
+ int right = s .length () - 1 ;
11
12
12
- for (int i = 0 ; i < str .length () / 2 ; i ++) {
13
- if (str .charAt (i ) != str .charAt (str .length () - 1 - i )) {
13
+ while (left < right ) {
14
+ char charLeft = s .charAt (left );
15
+ char charRight = s .charAt (right );
16
+ if (isNotValidCharacter (charLeft )) {
17
+ left ++;
18
+ continue ;
19
+ }
20
+ if (isNotValidCharacter (charRight )) {
21
+ right --;
22
+ continue ;
23
+ }
24
+
25
+ if (Character .toLowerCase (charLeft ) != Character .toLowerCase (charRight )) {
14
26
return false ;
15
27
}
28
+ left ++;
29
+ right --;
30
+ }
31
+ return true ;
32
+
33
+ }
34
+
35
+ private boolean isNotValidCharacter (char c ) {
36
+ if ((c >= '0' && c <= '9' )
37
+ || (c >= 'a' && c <= 'z' )
38
+ || (c >= 'A' && c <= 'Z' )) {
39
+ return false ;
16
40
}
17
41
return true ;
18
42
}
You can’t perform that action at this time.
0 commit comments