leetcode 125 Valid Palindrome
程序员文章站
2024-03-06 21:56:20
...
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
思路一:
- 首先是只考虑字符串中的字母和数字 把其他的都去掉 ;
- 所以想到先把字母和数字提取出来放到另外的一个字符串中 ;
- 然后再去判断这个字符串是不是回文串;
code:
bool isPalindrome(string s)
{
int len1=s.size();
if(len1<=1)
return true;
string str="";
int len2=0;
for(int i=0;i<len1;i++)
{
if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='z'))
{
str+=s[i];
len2++;
}
else if(s[i]>='A'&&s[i]<='Z')
{
str+=(s[i]-'A'+'a');
len2++;
}
}
int left=0;
int right=len2-1;
while(left<right)
{
if(str[left]!=str[right])
return false;
else
{
left++;
right--;
}
}
return true;
}
思路二:
直接在原字符串中处理 ;不是字母字符串的时候就直接循环遍历下一个 ;遇到是字符串或者是数字的才进行判断是不是回文串;
code:
bool isPalindrome(string s)
{
int n=s.size();
if(n<=1)return true;
int left=0;
int right=n-1;
while(left<right)
{
if(!isalnum(s[left]))
{
left++;
continue;
}
if(!isalnum(s[right]))
{
right--;
continue;
}
if(tolower(s[left++])!=tolower(s[right--]))
return false;
}
return true;
}
推荐阅读
-
[String][3]Leetcode125. Valid Palindrome
-
LeetCode125. Valid Palindrome
-
LeetCode 125: Valid Palindrome
-
Valid Palindrome II
-
Valid Palindrome II
-
leetcode 125 Valid Palindrome
-
LeetCode125. Valid Palindrome
-
[leetcode] Longest Valid Parentheses
-
LeetCode 193. Valid Phone Numbers
-
LeetCode Palindrome Partitioning