[LeetCode]Valid Palindrome
来源:互联网 发布:浩辰cad建筑软件 编辑:程序博客网 时间:2024/06/06 05:26
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.
这道题是判断一个字符串是否是回文字符串,有几个注意点:
1. 不区分大小写
2. 非数字和字母的字符忽略
3. 空字符串也认为是回文字符串
所以最一般的例子是形如,;‘’\n \t
的字符串,被视为空字符串,也就是回文的。
本来准备使用额外的空间来对字符串做个预处理,后来想想,还是不必了,头尾同时遍历的时候做个判断就可以了。遇到非数字字母的字符跳过,否则判断两字符是否“相等”:互为大小写或者完全相同。我处理的方式是两者相减,判断绝对值是否是0或者32.
下面贴上代码:
class Solution {public: bool isPalindrome(string s) { if (s.empty()) return true; int len = s.length(); int i = 0, j = len - 1; while (i <= j){ while (i<len&&!isalnum(s[i])) i++; while (j>=0&&!isalnum(s[j])) j--; if (i > j) return true; int num = abs(s[i] - s[j]); if (num != 0 && num != 32) return false; i++; j--; } return true; }};
0 0
- [Leetcode] Valid Palindrome
- Leetcode: Valid Palindrome
- leetcode 55: Valid Palindrome
- [LeetCode] Valid Palindrome
- 【leetcode】Valid Palindrome
- LeetCode - Valid Palindrome
- [leetcode]Valid Palindrome
- [LeetCode]Valid Palindrome
- [Leetcode]Valid Palindrome
- LeetCode-Valid Palindrome
- [leetcode] Valid Palindrome
- LeetCode 125: Valid Palindrome
- LeetCode - Valid Palindrome
- leetcode之Valid Palindrome
- LeetCode | Valid Palindrome
- [leetcode]Valid Palindrome
- 【leetcode】Valid Palindrome
- LeetCode题解:Valid Palindrome
- hdu 1423 Greatest Common Increasing Subsequence 最大公共上升子序列 DP
- 4.在Ubuntu为Android硬件抽象层(HAL)模块编写JNI方法提供Java访问硬件服务接口
- 搭建PHP环境
- 5.在Ubuntu上为Android系统的Application Frameworks层增加硬件访问服务
- SQL从一张表的某个字段更新为另一张表的字段
- [LeetCode]Valid Palindrome
- 6.在Ubuntu上为Android系统内置Java应用程序测试Application Frameworks层的硬件服务
- 【数据结构】静态链表
- 构造函数不能声明为虚函数,析构函数可以声明为虚函数
- iOS 内存管理ARC与mrc
- sersync同步多个目录
- MyEclipse在Debug模式下报cannot connect to vm
- oracle 11g 导出到10g
- Objective-c Run Time