-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidPalindrome.java
More file actions
executable file
·58 lines (53 loc) · 1.72 KB
/
Copy pathValidPalindrome.java
File metadata and controls
executable file
·58 lines (53 loc) · 1.72 KB
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
56
57
58
package string;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Author: Mr.Z
* @DateTime: 2021/01/16 20:57
* @Description: 125. 验证回文串 https://leetcode-cn.com/problems/valid-palindrome/
**/
public class ValidPalindrome {
public static boolean isPalindrome1(String s) {
// // 1.去除非字母字符,字母全转小写
// String str = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
// // 2.双指针
// int left = 0, right = str.length() - 1;
// while (left < right) {
// if (str.charAt(left) != str.charAt(right)) {
// return false;
// }
// left++;
// right--;
// }
// return true;
String str1 = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
String str2 = new StringBuffer(str1).reverse().toString();
return str1.equals(str2);
}
public boolean isPalindrome2(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
while (left <= right && !Character.isLetterOrDigit(s.charAt(left))) {
left++;
}
while (left <= right && !Character.isLetterOrDigit(s.charAt(right))) {
right--;
}
if (left <= right && Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
/**
* Main Method
*
* @param args
*/
public static void main(String[] args) {
String s = "abb";
System.out.println(isPalindrome1(s));
}
}