- 回文串
正读和反读都一样的字符串,比如“level”或者“noon”或者"a"
描述
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.
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串
例子
思路
- 双指针法
- 先把字符串变成有效字符串,再验证是否为回文
答案 - java
class Solution {
public boolean isPalindrome(String s) {
StringBuilder sb = new StringBuilder();
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if(c>='0' && c<='9') sb.append(c);
if(c>='a' && c<='z') sb.append(c);
if(c>='A' && c<='Z') sb.append((char)(c+32));
}
int i=0,j=sb.length()-1;
while(i<j) {
if(sb.charAt(i)!=sb.charAt(j)) return false;
i++;
j--;
}
return true;
}
}
- python
def isPalindrome(self, s: str) -> bool:
i=0
j = len(s)-1
while i<j: #当字符串为"a"时,直接略过该while,返回True,见下
if not s[i].isalnum():
i +=1
continue
if not s[j].isalnum():
j -= 1
continue
if s[i].lower()==s[j].lower():
i += 1
j -= 1
else:
return False
return True
- c++
bool isPalindrome(string s) {
int i=0,j=s.size()-1;
while (i<j)//当字符串为"a"时,直接略过该while,返回True,见下
{
if (!isalnum(s[i]))
{
i++;
continue;
}
if (!isalnum(s[j]))
{
j--;
continue;
}
if (tolower(s[i])==tolower(s[j]))
{
i++;
j--;
}
else
return false;
}
return true;
}