题目
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
思路
转换为小写,匹配字母和数字,两头开始比较,一样为true。
scala
object Solution {
def isPalindrome(s: String): Boolean = {
val chS = s.toLowerCase().toCharArray
val n = chS.length
var start = 0
var end = n -1
while(start < end){
while(!(chS(start) >= 'a' && chS(start) <= 'z') && !(chS(start) >= '0' && chS(start) <= '9') && start < end){
start = start + 1
}
while(!(chS(end) >= 'a' && chS(end) <= 'z') && !(chS(end) >= '0' && chS(end) <= '9') && start < end){
end = end - 1
}
if(chS(start) != chS(end)){
return false
}
start = start + 1
end = end - 1
}
true
}
}
// 别人的代码
object Solution {
def isPalindrome(s: String): Boolean = {
val ss = s.toLowerCase.filter(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'z'))
ss == ss.reverse
}
}
java
class Solution {
public boolean isPalindrome(String s) {
char[] chS = s.toLowerCase().toCharArray();
int n = chS.length;
int start = 0;
int end = n - 1;
while (start < end) {
while (!(chS[start] >= 'a' && chS[start] <= 'z') && !(chS[start] >= '0' && chS[start] <= '9') && start < end) {
start++;
}
while (!(chS[end] >= 'a' && chS[end] <= 'z') && !(chS[end] >= '0' && chS[end] <= '9') && start < end) {
end--;
}
if (chS[start] != chS[end]) {
return false;
}
start++;
end--;
}
return true;
}
}