leetCode题解之判断一个句子中的字符和数字是否构成回文

1、问题描述

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.

输入一个字符串,判断这个字符中所有的数字和字母字符是否是回文,大小写相同。

如果空字符串是回文字符串。

2、问题分析

   首先想到的是可以将该字符串中的所有的数字和字母放入一个 string 或者vector ,然后判断,这样需要额外申请空间。

  第二种方法是直接使用两个指针,一个向前遍历,一个向后遍历。遇到非字符和数字则跳过,遇到字符和数字则判断。

3、代码

 1 bool isPalindrome(string s) {
 2         if( s.size() == 0 )
 3         {
 4             return true;
 5         }
 6         
 7     for(int i = 0,j = s.size()-1; i < j;i++,j--)
 8     {
 9         while( !isalnum(s[i]) && i < j) i++;
10         while( !isalnum(s[j]) && i < j) j--;
11         if(toupper(s[i]) != toupper(s[j]) )
12             return false;
13     }
14         
15         return true;
16         
17         
18     }
pp
原文地址:https://www.cnblogs.com/wangxiaoyong/p/8669495.html