LeetCode Note Java 00125:Valid Palindrome

判斷將字串除去符號與轉成小寫後是否回文。

題目

Valid Palindrome Easy

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

我的解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public boolean isPalindrome(String s) {
String ls = s.toLowerCase();
int left = 0, right = ls.length() - 1;
while (left < right) {
if (!Character.isLetterOrDigit(ls.charAt(left))) {
left++;
continue;
}
if (!Character.isLetterOrDigit(ls.charAt(right))) {
right--;
continue;
}
if (ls.charAt(left) != ls.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}

重點物件或方法

  • Character.isLetterOrDigit()

檢討

最難的就是判斷是不是符號,如果不會這個方法就很難寫出來。