题目要求:
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 class Solution { 2 public: 3 bool isPalindrome(string s) { 4 if(!s.empty() && s.front() == ‘ ‘) 5 s.erase(0, 1); 6 if(!s.empty() && s.back() == ‘ ‘) 7 s.pop_back(); 8 9 bool ret = true; 10 int sz = s.size(); 11 if(sz == 0) 12 return true; 13 14 int i = 0; 15 int j = sz - 1; 16 while(i < j) 17 { 18 while(i < sz && !isalnum(s[i])) 19 i++; 20 while(j > -1 && !isalnum(s[j])) 21 j--; 22 if(i < sz && j > -1 && s[i] != s[j]) 23 { 24 if(tolower(s[i]) != tolower(s[j])) 25 { 26 ret = false; 27 break; 28 } 29 } 30 i++; 31 j--; 32 } 33 34 return ret; 35 } 36 };
时间: 2024-11-12 07:06:29