125. Valid Palindrome

https://leetcode.com/problems/valid-palindrome/

String –> Two Pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
/**
* Character.isLetterOrDigit(char ch)
*/
boolean isLetterandDigit(char ch) {
return ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';
}

boolean isPalindromeUtil(String s, int start, int end) {
while (start < end) {
while(!isLetterandDigit(s.charAt(start))&&start<end) start++;
while(!isLeisLetterandDigittter(s.charAt(end))&&end>start) end--;
if (s.charAt(start) != s.charAt(end)) return false;
start++;
end--;
}
return true;
}

public boolean isPalindrome(String s) {
s = s.trim().toLowerCase();
return isPalindromeUtil(s, 0, s.length() - 1);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Regualr expression
String removeNoneLD(String s) {
return s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
}

// String removeNoneLD(String s) {
// for (int i = 0; i < s.length(); i++) {
// if (!isLetterandDigit(s.charAt(i))) {
// s = s.substring(0, i) + s.substring(i + 1);
// i--;
// }
// }
// return s.trim().toLowerCase();
// }

0%