[leetcode]16 Valid Palindrome
来源:互联网 发布:有关人工智能的文献 编辑:程序博客网 时间:2024/06/10 00:45
题目连接:https://oj.leetcode.com/problems/valid-palindrome/
Runtimes:16ms
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.
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.
2、分析
检查一个字符串是否是回文字符串,只考虑数字和字母(忽略大小写)。定义头尾两个下标i,j,往中间扫描,遇到非字母数字跳过,遇到都是字母检查是否相等。直到i > j结束。
3、小结
该字符串是一个句子,包含标点符号,但是题目要求只考虑数字字母,因此需要跳过符号,其次大小写字母的ASCII码相差32。只需一次线性扫描,时间复杂度为O(n),空间复杂度为O(1)。
4、实现
class Solution {public: bool isLetter(char a) { if ((a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z') || (a >= '0' && a <= '9')) { return true; } else return false; } bool isEqual(char a, char b) { if (a == b || a - b == 32 || a - b == -32) return true; else return false; } bool isPalindrome(string s) { for (int i = 0, j = s.size() - 1; i < j;) { while (!isLetter(s[i])) i++; while (!isLetter(s[j])) j--; if (i < j && !isEqual(s[i], s[j])) { return false; } else{ i++; j--; } } return true; }};
5、反思
程序比较简单,但是在写的过程中也出现’==’写成’=’,’a <= ‘a”写成’a < ‘a”的低级错误。代码中也把空字符串也当做回文串处理。
文章链接:http://blog.csdn.net/linhuanmars/article/details/22775045
- [leetcode]16 Valid Palindrome
- LeetCode (16) Valid Palindrome (回文)
- [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
- C++语言基础 例程 类的成员函数
- C++语言基础 例程 对象成员的引用
- C++语言基础 例程 类和对象的简单应用举例
- 一切成功源于积累——20150307 美国非农5分钟k线直至收盘 各货币对表现
- WCF系列_分布式事务(下)
- [leetcode]16 Valid Palindrome
- Qdebug在qt调试中的应用
- C#工厂模式-工厂方法
- android activity 传值
- 分类信息网站排名,终身VIP制-辛有才分类信息网
- Robotium中调用getActivity()方法导致程序挂起的研究浅析
- Y470 Y570 UEFI 2.12BIOS(64位)
- fatal error LNK1281: 无法生成 SAFESEH 映像。
- 优化多说插件的加载速度