Valid Palindrome
2016-07-14 20:36
429 查看
一、问题描述
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
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.
Subscribe to see which companies asked this question
二、思路
版本一:暴力求解。将数字和字符串存储在另一个字符串中,将大写字母全部变为小写字母,判断是否是回文串。超时
版本二:采用两个库函数,isalnum()函数识别是否是子母和数字;tolower()将所有的大写字母变为小写字母,其余字符不做处理。
三、代码
版本一:超时不通过
版本二
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.
Subscribe to see which companies asked this question
二、思路
版本一:暴力求解。将数字和字符串存储在另一个字符串中,将大写字母全部变为小写字母,判断是否是回文串。超时
版本二:采用两个库函数,isalnum()函数识别是否是子母和数字;tolower()将所有的大写字母变为小写字母,其余字符不做处理。
三、代码
版本一:超时不通过
class Solution { public: bool isPalindrome(string s) { string t = ""; if(s == "") return true; for(int i = 0; i < s.size(); ++i) if(s[i] >= 65 && s[i] <= 90 || s[i] >= 97 && s[i] <= 122 || s[i] >= 48 && s[i] <= 57) t = t + s[i]; for(int l = 0; l < t.size(); ++l) if(t[l] >= 65 && t[l] <= 90) t[l] += 32; for(int j = 0,k = t.size() - 1; j < k; ++j,--k) if(t[j] != t[k]) return false; return true; } };
版本二
class Solution { public: bool isPalindrome(string s) { int i = 0,j = s.size() - 1; while(i < j){ while(!isalnum(s[i]) && i < j) i++; while(!isalnum(s[j]) && i < j) j--; if(tolower(s[i++]) != tolower(s[j--])) return false; } return true; } };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解