Valid Palindrome
来源:互联网 发布:mac截屏保存在哪里 编辑:程序博客网 时间:2024/06/10 00:35
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.
Two Pointers String
思路:1.回文只识别字母和数字;
2.大小写视为一样;
3.sting不是以'\0'结尾,所以用substr函数处理。
class Solution {public: char lowerCase(char c){if (c >= 'A' && c <= 'Z')return c - 'A' + 'a';elsereturn c;}bool isPalindrome(string s) {int len = s.length();string temp(len,0);//因为空串不能用下标访问和赋值,所以得初始化int i = 0,j = 0;while (i < len){if (isalpha(s.at(i))){temp.at(j++) = s.at(i++);}else if (s.at(i) >= '0' && s.at(i) <= '9') {temp.at(j++) = s.at(i++);}else i++;}//temp.at(j) = '\0';string类型不是以'\0'结尾temp = temp.substr(0, j);//从第0位取到第j位int len1 = temp.length();cout << len1 <<endl;for (int i = 0; i < len1/2; i++){if (lowerCase(temp[i]) == lowerCase(temp[len1 - 1 - i])){continue;}elsereturn false;}return true;}};测试:27 ms
void main(){Solution s;string a;getline(cin, a);cout << s.isPalindrome(a);}
主要难点在于提供接口是string类型,需了解一些基本函数。
代码太冗余,经优化后:16 ms
//判断是否为字母、数字//bool isalphanumeric(char c){函数执行完后,数组元素还是不会变为小写 bool isalphanumeric(char &c){if ((c >= 'A'&&c <= 'Z')){//大写则转换成小写c = c - 'A' + 'a';return true;}return (c >= '0'&&c <= '9') || (c >= 'a'&&c <= 'z');} bool isPalindrome(string s) {int len = s.length();int i = 0, j = len - 1;while (i<j){if (!isalphanumeric(s[i])) {i++;continue;//跳出}if (!isalphanumeric(s[j])) {j--;continue;//跳出}if (s[i] != s[j]) return false;else i++, j--;}return true;}
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
- SpringMVC和Hibernate整合
- Windows远程桌面访问Ubuntu 12.04 之安装XRDP
- makefile中的patsubst/notdir/patsubst
- 一步一步教你做ios推送
- Logo
- Valid Palindrome
- 未来的自己
- 创建运行ArcGis JS API 项目
- Cocos2d-x Lua中Sprite精灵类
- iOS 消息推送原理及实现Demo
- LeetCode ---Valid Palindrome
- iOS Developer:真机测试
- SpringMVC+Spring4.0+Hibernate 简单的整合
- Socket -tcp/ip