Valid Palindrome
来源:互联网 发布:小程序源码上传服务器 编辑:程序博客网 时间:2024/06/07 03:05
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.
思路
判断回文可以使用经典的两头加逼的方法。即使用一个指针指向字符串首部,另一个指针指向字符串尾部。比较被指向的两个字符,如果不等,不是回文,中止比较;如果相等,两个指针各自向中间移动。如此重复直到两指针相交或有字符不等。如判断raceacar:
下标0,r = 下标7,r
下标1,a = 下标6,a
下标2,c = 下标5,c
下标3,e != 下标4,a ==》不为回文。
由于题目的一些限制,在处理时还要注意一些细节:
- 非字母数字字符不参加判断,我们在每次移动指针(下标)时都需要有一个循环跳过这些字符。循环的终止条件为两指针(下标)相交或者指向了一个字母数字字符。
- 非字母数字字符可使用isalnum函数判断。
- 忽略大小写,可在比较字符前统一使用tolower将两个字符皆转成小写。
#include<iostream>#include<string>#include<algorithm>#include<stack>using namespace std;int main(){string s = "2abc,,c,b,,A2";bool sign = true;int n = s.length();int i = 0;int j = n - 1;while (i < j){if (!((s[i] >= 'A'&&s[i] <= 'Z') || (s[i] >= 'a' &&s[i] <= 'z'))){i++;continue;}if (!((s[j] >= 'A'&&s[j] <= 'Z') || (s[j] >= 'a' &&s[j] <= 'z'))){j--;continue;}if ((s[i] >= 'A'&&s[i] <= 'Z')){s[i] = s[i] - 'A' + 'a';}if ((s[j] >= 'A'&&s[j] <= 'Z')){s[j] = s[j] - 'A' + 'a';}if (s[i] != s[j]){sign = false;break;}else{i++;j--;}}cout << sign << endl;system("pause");return 0;}
class Solution {public: bool isPalindrome(string s) { int n = s.size(); int i=0, j=n-1; while(i<j){ if( !isalpha(s[i]) ) { ++i; continue; } if( !isalpha(s[j]) ) { --j; continue; } if(s[i] != s[j]) return false; ++i,--j; } return true; } //判断是否是字母数字,如果是大写字母则将其转化为小写字母 bool isalpha(char &c){ if((c>='A'&&c<='Z')){ c = c-'A'+'a'; return true; } return (c>='a'&&c<='z') || (c>='0'&&c<='9'); }};
0 0
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- valid palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- 15泛型_15.1与C++比较
- Java的接口问题
- DWZ学习总结《一》
- Android studio修改变更Eclipse快捷键
- Using Process Memory Matrix script for understanding Oracle process memory usage
- Valid Palindrome
- PHP - 解决中文乱码问题
- SharedPreference用法
- C#----计算器例子
- 哈希表的实现
- Java的一些经验
- 面试时应该如何进行自我介绍呢
- Android OS--Looper、Thread、Handler
- Cocos2D iOS之旅:如何写一个敲地鼠游戏(四):创建TexturePacker自动脚本