-
Notifications
You must be signed in to change notification settings - Fork 1
/
125. Valid Palindrome.java
47 lines (34 loc) · 1000 Bytes
/
125. Valid Palindrome.java
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
38
39
40
41
42
43
44
45
46
47
// space - O(2n) and time - O(n)
class Solution {
public boolean isPalindrome(String s) {
s = s.replaceAll("[^a-zA-Z0-9]","");
s = s.replaceAll(" ","");
s = s.toLowerCase();
StringBuilder str = new StringBuilder(s);
return (str.reverse().toString().equalsIgnoreCase(s));
}
}
//constant space complexity and time complexity - space- O(1), time - O(n)
class Solution {
public boolean isPalindrome(String s) {
s = s.replaceAll("[^a-zA-Z0-9]","");
s = s.replaceAll(" ","");
s = s.toLowerCase();
int left = 0;
int right = s.length()-1;
while(left<right)
{
if(s.charAt(left) == s.charAt(right))
{
left = left+1;
right = right-1;
continue;
}
else
{
return false;
}
}
return true;
}
}