长大后想做什么?做回小孩!

0%

LeetCode——验证回文串

NO.125 验证回文串 简单

J6haSU.png

思路一:双指针 没什么好说的,API转换为小写即忽略大小写,用API跳过非字母或数字字符。

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
public boolean isPalindrome(String s) {
if (s == null) return true;
//忽略大小写
String lower = s.toLowerCase();
//双指针
int i = 0, j = lower.length() - 1;
while (i < j) {
char ci = lower.charAt(i);
char cj = lower.charAt(j);
//不是字符或数字跳过
if (!Character.isLetterOrDigit(ci)) {
i++;
continue;
}
if (!Character.isLetterOrDigit(cj)) {
j--;
continue;
}
//不相等false
if (ci != cj) {
return false;
} else {
i++;
j--;
}
}
return true;
}

时间复杂度:O(n)


本人菜鸟,有错误请告知,感激不尽!

更多题解和源码:github