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.
思路:
将原字符串去掉非字母和数字,全部转化为小写,在判断回文
代码:
1 bool isPalindrome(string s) { 2 // Start typing your C/C++ solution below 3 // DO NOT write int main() function 4 string t = ""; 5 for (int i = 0; i < s.length(); i++) { 6 if (s[i] >= 'a' && s[i] <= 'z' || s[i] >= '0' && s[i] <= '9' || s[i] >= 'A' && s[i] <= 'Z') { 7 if (s[i] >= 'A' && s[i] <= 'Z') { 8 t += (s[i] - 'A' + 'a'); 9 } 10 else { 11 t += s[i]; 12 } 13 } 14 } 15 if (t == "") { 16 return true; 17 } 18 for (int i = 0; i < t.length() / 2; i++) { 19 if (t[i] != t[t.length() - i - 1]) { 20 return false; 21 } 22 } 23 return true; 24 }