Article Directory
topic:
Given a string, verify whether it is a palindrome, only consider letters and numbers, and ignore the case of letters.
Explanation: In this question, we define an empty string as a valid palindrome string.
Example 1:
输入: "A man, a plan, a canal: Panama"
输出: true
Example 2:
输入: "race a car"
输出: false
Solution 1: Violence
/**
* 思路:
* 过滤出需要的字符
* 反转字符串
* 比较反转前后的字符串
*/
public boolean isPalindrome(String s) {
String filterS=isLetterORDigit(s);
String reversS=reverse(filterS);
return filterS.equalsIgnoreCase(reversS);
}
private String reverse(String filterS) {
StringBuilder sb = new StringBuilder(filterS);
sb.reverse();
return sb.toString();
}
private String isLetterORDigit(String s) {
return s.replaceAll("[^0-9a-zA-Z]","");
}
Time complexity: On
Space complexity: On
Solution 2: Double pointer
/**
* 思路:
* 过滤出需要的字符
* 头尾比较
*/
pub
public boolean isPalindrome(String s) {
StringBuilder sb = new StringBuilder();
for (int i=0;i<s.length();i++){
char c = s.charAt(i);
if (Character.isLetterOrDigit(c)){
sb.append(Character.toLowerCase(c));
}
}
int l=0,r=sb.length()-1;
while (r>l){
if (sb.charAt(l++)!=sb.charAt(r--))return false;
}
return true;
}
Time complexity: On
Space complexity: On