125. 验证回文串
一、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++
#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
class Solution:def isPalindrome(self, s: str):l, r = 0, len(s) - 1while l < r:while l < r and not s[l].isalnum():l += 1while l < r and not s[r].isalnum():r -= 1if l < r and s[l].lower() != s[r].lower():return Falsel, r = l + 1, r - 1return True
四、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
package mainimport "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
}