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.
验证回文与否,这个估计大家学c语言的时候就都写过:
1 class Solution { 2 public: 3 bool isPalindrome(string s) { 4 int len = s.length(); 5 for(int i = 0, j = len - 1; i < j ;++i, --j){ 6 while(i < j && (!isalpha(s[i]) && !isdigit(s[i]))) 7 i++; 8 while(j > i && (!isalpha(s[j]) && !isdigit(s[j]))) 9 j--; 10 if(isalpha(s[i]) && isalpha(s[j])){ 11 if(toupper(s[i]) == toupper(s[j])) 12 continue; 13 else return false; 14 }else{ 15 if(s[i] == s[j]) 16 continue; 17 return false; 18 } 19 } 20 return true; 21 } 22 };
java版本的代码如下所示,算法没有变化:
public class Solution { public boolean isPalindrome(String s) { int sz = s.length(); int beg = 0, end = sz - 1; while(beg < end){ while(!Character.isLetter(s.charAt(beg)) && !Character.isDigit(s.charAt(beg))){ if(beg < end) beg++; else return true; } while(!Character.isLetter(s.charAt(end)) && !Character.isDigit(s.charAt(end))){ if(beg < end) end--; else return true; } if(Character.toUpperCase(s.charAt(beg)) == Character.toUpperCase(s.charAt(end))){ beg++; end--; }else{ return false; } } return true; } }