Description
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input:
"A man, a plan, a canal: Panama"
Output:
true
Example 2:
Input:
"race a car"
Output:
false
分析
题目的意思是:判断一个字符串是否是回文子串。
- 本题是判断回文子串,用两个索引,分别指向字符串的开头和结尾,其中注意大小写的相等比较,还有要跳过空格和标点不好。
- 这道题在牛课网上通过了但在leetcode上没有通过,".“和” "没有判断出来,我家了if(i>j)的操作,然后accept了,看来leetcode更难一点。
C++实现
class Solution {
public:
bool isPalindrome(string s) {
int i=0;
int j=s.length()-1;
while(i<=j){
while(i<=j&&!isalnum(s[i])){
i++;
}
while(i<=j&&!isalnum(s[j])){
j--;
}
if(i>j){
return true;
}
if(tolower(s[i])==tolower(s[j])){
i++;
j--;
}else{
return false;
}
}
return true;
}
};
Python实现
用python写了一个暴力解法。
class Solution:
def isPalindrome(self, s: str) -> bool:
i = 0
j = len(s)-1
while i<=j:
if not s[i].isupper() and not s[i].islower() and not s[i].isalnum():
i+=1
elif not s[j].isupper() and not s[j].islower() and not s[j].isalnum():
j-=1
elif s[i].lower()!=s[j].lower():
return False
else:
i+=1
j-=1
return True
下面来一个变换版本:
class Solution:
def isPalindrome(self, s: str) -> bool:
n = len(s)
left = 0
right = n-1
while left<right:
while left<right and not s[left].isalnum():
left+=1
while left<right and not s[right].isalnum():
right-=1
if left<right:
if s[left].lower()!=s[right].lower():
return False
left+=1
right-=1
return True
上面的代码调用的API比较多,下面的简洁一点,只调用了isalnum,lower的API:
class Solution:
def isPalindrome(self, s: str) -> bool:
sgood = ""
for ch in s:
if ch.isalnum():
sgood+=ch.lower()
n = len(sgood)
left = 0
right = n-1
while left<right:
if sgood[left]!=sgood[right]:
return False
left+=1
right-=1
return True