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;
}
};
Python Code:
classSolution:defisPalindrome(self,s:str) ->bool: left, right =0,len(s)-1while left < right:ifnot s[left].isalnum(): left +=1continueifnot s[right].isalnum(): right -=1continueif s[left].lower()== s[right].lower(): left +=1 right -=1else:breakreturn right <= leftdefisPalindrome2(self,s:str) ->bool:""" 使用语言特性进行求解 """ s =''.join(i for i in s if i.isalnum()).lower()return s == s[::-1]
Java Code:
classSolution {publicbooleanisPalindrome(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))) {returnfalse; }++left;--right; } }returntrue; }}
复杂度分析
时间复杂度:$O(N)$
空间复杂度:$O(1)$
大家对此有何看法,欢迎给我留言,我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 37K star 啦。 大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。