-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidPalindrome.java
55 lines (51 loc) · 1.62 KB
/
ValidPalindrome.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
48
49
50
51
52
53
54
55
public class ValidPalindrome {
public static void main(String[] args) {
System.out.println(isPalindrome("race a car"));
}
//my solution
public static boolean isPalindrome(String s) {
StringBuffer str = makeStringArr(s);
if (str.length() <= 1 || s.equals(" ")) return true;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != str.charAt(str.length() - i - 1))
return false;
}
return true;
}
public static StringBuffer makeStringArr(String s) {
s = s.toLowerCase().replace(" ", "");
StringBuffer str = new StringBuffer(s);
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) < 97 || str.charAt(i) > 122) {
if(str.charAt(i)>=48 && str.charAt(i) <=57)
continue;
else {
str.deleteCharAt(i);
i--;
}
}
}
System.out.println(str);
return str;
}
// best solution
public boolean isPalindrome_bs(String s) {
int left = 0, right = s.length()-1;
while(left < right) {
if (!Character.isLetterOrDigit(s.charAt(left))) {
left++;
continue;
}
if (!Character.isLetterOrDigit(s.charAt(right))) {
right--;
continue;
}
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
}