Skip to content

Commit 5985790

Browse files
committed
判断回文字符串
1 parent 9d0d6f8 commit 5985790

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,7 @@
201201
- [String](/algorithm/LeetCode/String.md)
202202
- [Restore IP Addresses](/algorithm/LeetCode/String/ip.md)
203203
- [Rotate String](/algorithm/LeetCode/String/Rotate-String.md)
204+
- [Valid Palindrome](/algorithm/LeetCode/String/Valid-Palindrome.md)
204205

205206
## 设计模式
206207

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
## 一、题目
2+
3+
> Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
4+
>
5+
> For example,
6+
> `"A man, a plan, a canal: Panama"` is a palindrome.
7+
> `"race a car"` is *not* a palindrome.
8+
>
9+
> **Note:**
10+
>
11+
> Have you consider that the string might be empty? This is a good question to ask during an interview.
12+
>
13+
> For the purpose of this problem, we define empty string as valid palindrome.
14+
15+
判断一个字符串是不是回文串。
16+
17+
## 二、解题思路
18+
19+
字符串的回文判断问题,由于字符串可随机访问,故逐个比较首尾字符是否相等最为便利,即常见的『两根指针』技法。
20+
21+
两步走:
22+
23+
1. 找到最左边和最右边的第一个合法字符(字母或者字符)
24+
2. 一致转换为小写进行比较
25+
26+
## 三、解题代码
27+
28+
```java
29+
public class Solution {
30+
public boolean isPalindrome(String s) {
31+
if (s == null || s.trim().isEmpty()) {
32+
return true;
33+
}
34+
35+
int l = 0, r = s.length() - 1;
36+
while (l < r) {
37+
if(!Character.isLetterOrDigit(s.charAt(l))) {
38+
l++;
39+
continue;
40+
}
41+
if(!Character.isLetterOrDigit(s.charAt(r))) {
42+
r--;
43+
continue;
44+
}
45+
if (Character.toLowerCase(s.charAt(l)) == Character.toLowerCase(s.charAt(r))) {
46+
l++;
47+
r--;
48+
} else {
49+
return false;
50+
}
51+
}
52+
53+
return true;
54+
}
55+
}
56+
```
57+

0 commit comments

Comments
 (0)