一、Java
java
class Solution {
public boolean isPalindrome(String s) {
for (int l = 0, r = s.length() - 1; l < r; l++, r--) {
while (l < r && !Character.isLetterOrDigit(s.charAt(l))) l++;
while (l < r && !Character.isLetterOrDigit(s.charAt(r))) r--;
if (l < r && Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))) return false;
}
return true;
}
}
二、C++
cpp
#include <string>
using namespace std;
class Solution {
public:
bool isPalindrome(string s) {
for (int l = 0, r = s.size() - 1; l < r; l++, r--) {
while (l < r && !isalnum(s[l])) l++;
while (l < r && !isalnum(s[r])) r--;
if (l < r && tolower(s[l]) != tolower(s[r])) return false;
}
return true;
}
};
三、Python
python
class Solution:
def isPalindrome(self, s: str):
l, r = 0, len(s) - 1
while l < r:
while l < r and not s[l].isalnum():
l += 1
while l < r and not s[r].isalnum():
r -= 1
if l < r and s[l].lower() != s[r].lower():
return False
l, r = l + 1, r - 1
return True
四、JavaScript
javascript
var isPalindrome = function(s) {
for (let l = 0, r = s.length - 1; l < r; l++, r--) {
while (l < r && !/[a-zA-Z0-9]/.test(s[l])) l++;
while (l < r && !/[a-zA-Z0-9]/.test(s[r])) r--;
if (l < r && s[l].toLowerCase() !== s[r].toLowerCase()) return false;
}
return true;
};
五、Go
Go
package main
import "unicode"
func isPalindrome(s string) bool {
for l, r := 0, len(s)-1; l < r; l, r = l+1, r-1 {
for l < r && !unicode.IsDigit(rune(s[l])) && !unicode.IsLetter(rune(s[l])) {
l++
}
for l < r && !unicode.IsDigit(rune(s[r])) && !unicode.IsLetter(rune(s[r])) {
r--
}
if l < r && unicode.ToLower(rune(s[l])) != unicode.ToLower(rune(s[r])) {
return false
}
}
return true
}