letecode [125] - Valid Palindrome
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
题目大意:
给定一个字符串判断是否为回文串。回文串即从左到右读和从右到左读是一样的。字符串中只考虑字母和数字。
理 解:
设置两个指针,一个从首端开始,一个从末端开始,比较两个字符是否满足条件。满足条件则指针移动,直到字符串遍历完;一旦出现不满足的条件,即判断为非回文串。
主要考虑几种情况:
1.两个被比较的字符均为字母或数字,则判断它们是否相等(字母不考虑大小写,可以把字符串统一转换:转小写strlwr、转大写strupr)。
相等则移动指针,否则为非回文串。
2.两个被比较的字符不为字母或数字,则直接移动指针。
代 码 C++:
class Solution { public: bool isPalindrome(string s) { if(s=="") return true; int n = s.length(); int i=0,j=n-1; while(i<j){ // alphabet:A-65,a-97 digit:0-48 if((isalpha(s[i])||isdigit(s[i]))&&(isalpha(s[j])||isdigit(s[j]))){ if(isalpha(s[i])) s[i] = toupper(s[i]); if(isalpha(s[j])) s[j] = toupper(s[j]); if(s[i]==s[j]){ ++i; --j; }else{ return false; } }else if(!isalpha(s[i])&&!isdigit(s[i])){ ++i; if(!isalpha(s[j])&&!isdigit(s[j])) --j; }else{ --j; } } return true; } };
运行结果:
执行用时 : 12 ms 内存消耗 : 9.6 MB

浙公网安备 33010602011771号