28. Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
125. Valid Palindrome 有效回文串
判断一个字符串是否是回文串,除字母数字外其他的字符不考虑,不考虑大小写的区别
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.
使用双指针,注意事项是大写字母的ASCII比小写字母小
另外这里不区分大小写字母, 运行不通过
class Solution {
public:
bool isPalindrome(string s) {
if(!s.size()) return true;
int n=s.size();
int first=0,last=n-1;
while(first<last)
{
while(first<last&&(s[first]<'A'||s[first]>'z')&&(s[first]<'0'||s[first]>'9')) first++;
while(first<last&&(s[last]<'A'||s[last]>'z')&&(s[last]<'0'||s[last]>'9')) last--;
if(first<last&&s[first]!=s[last])
{
if(s[first]>='A'&&s[first]<'z'&&s[last]>='A'&&s[last]<='z')
{
if(s[first]!=s[last]+'a'-'A'&&s[first]!=s[last]+'A'-'a')
return false;
else break;
}
else return false;
}
first++;
last--;
}
return true;
}
};
简易:使用两个库函数
class Solution {
public:
bool isPalindrome(string s) {
int n=s.size();
int i=0,j=n-1;
while(i<j)
{
while(i<j&&isalnum(s[i])==false) i++;
while(i<j&&isalnum(s[j])==false) j--;
if(toupper(s[i])!=toupper(s[j])) return false;
i++;
j--;
}
return true;
}
};