Skip to content

Commit 09c8095

Browse files
committed
refactor: valid-palindrome space complexity
1 parent bff3394 commit 09c8095

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

valid-palindrome/minji-go.java

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,41 @@
22
* <a href="https://leetcode.com/problems/valid-palindrome/">week03-1.valid-palindrome</a>
33
* <li>Description: return true if it is a palindrome </li>
44
* <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>
77
*/
88
class Solution {
99
public boolean isPalindrome(String s) {
10-
String str = s.toLowerCase().replaceAll("[^0-9a-z]", "");
10+
int left = 0;
11+
int right = s.length() - 1;
1112

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)) {
1426
return false;
1527
}
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;
1640
}
1741
return true;
1842
}

0 commit comments

Comments
 (0)