题目
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
“A man, a plan, a canal: Panama” is a palindrome.
“race a car” is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
题意
给你一个字符串,判断是否为回文字符串。
回文字符串的定义:
只比较数字和字符,忽略其他字符,不考虑字符大小写。
题解
- 把字符串中的字符全部转换为小写字符。
- 拿左边的元素和右面的元素比较。会出现三种情况
- 左边字符不属于数字和字符,跳到左边下一个。
- 右边字符不属于数字和字符,跳到右边下一个。
- 左右字符均合法,比较两字符是否相同:
1. 相同,左右同时跳到下一个
2. 不同,直接结束,可以判断此字符串不是合法的回文串。
- 左边指针指向大于右边指针指向,结束,为合法的回文串。
Python语言
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower(); #字母全部转换为小写
start = 0
end = len(s)-1
if len(s)==0 or len(s)==1:
return True
while start<=end: #同时从比较左右对应元素是否相同
if (s[start]<"a" or s[start] > "z") and (s[start] < "0" or s[start] > "9"): #左边的元素既不是字符又不是数组,跳到下一个
start = start + 1
elif (s[end]<"a" or s[end] > "z") and (s[end] < "0" or s[end] > "9"):#同样处理右边的元素
end = end - 1
else:
if s[start] == s[end]:#相同比较下一个
start = start + 1
end = end - 1
else:#只有一出现不相同的即不为回文字符串
return False
return True
C++语言
class Solution {
public:
bool isPalindrome(string s) {
int start = 0;
int end = s.length() - 1;
string temp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
if(s.length()==0||s.length()==1)
return true;
while(start <= end)
{
if(temp.find(s[start])<0||temp.find(s[start])>61)
start++;
else if(temp.find(s[end])<0||temp.find(s[end])>61)
end--;
else
{
if(((s[start]-32==s[end] || s[start]+32==s[end])&&(temp.find(s[start])>=0&&temp.find(s[start])<=51&&temp.find(s[end])>=0&&temp.find(s[end])<=51)) || s[start] == s[end])
{
start++;
end--;
}
else
return false;
}
}
return true;
}
};