File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed
algorithm/LeetCode/String Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change 201
201
- [ String] ( /algorithm/LeetCode/String.md )
202
202
- [ Restore IP Addresses] ( /algorithm/LeetCode/String/ip.md )
203
203
- [ Rotate String] ( /algorithm/LeetCode/String/Rotate-String.md )
204
+ - [ Valid Palindrome] ( /algorithm/LeetCode/String/Valid-Palindrome.md )
204
205
205
206
## 设计模式
206
207
Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments