Valid Palindrome

Description:

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.

Code:

 1  bool isPalindrome(string s) {

 2         int p = 0;

 3         int q = s.length()-1;

 4       

 5         while ( p <= q )

 6         {

 7             while ( !isalnum(s[p]) && p < q)

 8                 ++p;

 9             while ( !isalnum(s[q]) && p < q)

10                 --q;

11                 

12             if ( p > q )

13                 break;

14                 

15             s[p] = isupper(s[p]) ? tolower(s[p]) : s[p];

16             s[q] = isupper(s[q]) ? tolower(s[q]) : s[q];

17             

18             if ( s[p] != s[q] )

19                 return false;

20             else

21             {

22                 ++p;

23                 --q;

24             }

25         }

26         return true;

27     }

 

你可能感兴趣的:(ROM)