0125. 验证回文串
最后更新于
这有帮助吗?
这有帮助吗?
/*
* @lc app=leetcode id=125 lang=javascript
*
* [125] Valid Palindrome
*/
// 只处理英文字符(题目忽略大小写,我们前面全部转化成了小写, 因此这里我们只判断小写)和数字
function isValid(c) {
const charCode = c.charCodeAt(0);
const isDigit =
charCode >= "0".charCodeAt(0) && charCode <= "9".charCodeAt(0);
const isChar = charCode >= "a".charCodeAt(0) && charCode <= "z".charCodeAt(0);
return isDigit || isChar;
}
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
s = s.toLowerCase();
let left = 0;
let right = s.length - 1;
while (left < right) {
if (!isValid(s[left])) {
left++;
continue;
}
if (!isValid(s[right])) {
right--;
continue;
}
if (s[left] === s[right]) {
left++;
right--;
} else {
break;
}
}
return right <= left;
};class Solution {
public:
bool isPalindrome(string s) {
if (s.empty())
return true;
const char* s1 = s.c_str();
const char* e = s1 + s.length() - 1;
while (e > s1) {
if (!isalnum(*s1)) {++s1; continue;}
if (!isalnum(*e)) {--e; continue;}
if (tolower(*s1) != tolower(*e)) return false;
else {--e; ++s1;}
}
return true;
}
};class Solution:
def isPalindrome(self, s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
if not s[left].isalnum():
left += 1
continue
if not s[right].isalnum():
right -= 1
continue
if s[left].lower() == s[right].lower():
left += 1
right -= 1
else:
break
return right <= left
def isPalindrome2(self, s: str) -> bool:
"""
使用语言特性进行求解
"""
s = ''.join(i for i in s if i.isalnum()).lower()
return s == s[::-1]class Solution {
public boolean isPalindrome(String s) {
int n = s.length();
int left = 0, right = n - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
++left;
}
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
--right;
}
if (left < right) {
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
++left;
--right;
}
}
return true;
}
}