leetcode | Valid Palindrome
2015-06-21 16:44
375 查看
Valid Palindrome : https://leetcode.com/problems/valid-palindrome/
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. 全空格字符串应判断为true
2. 字母不区分大小写
一种算法就是,将原字符串剔除所有非字母数字字符,插入到一个新的字符串空间,然后基于新字符串,用2个指针法做判断。算法实现简单,不需额外考虑全空格字符串,但是占用额外空间。
另一种算法是,用2个指针指向字符串两头,当遇到非字母数字字符时跳过,然后做处理。对于全空格字符串,通过判断左指针是否会到达字符串尾部。,优点是不占用额外空间,时间复杂度上也优于第一种(只需遍历一次数组)。
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.
解析
alphanumeric characters :字母或数字型字符本题难点在于:
1. 全空格字符串应判断为true
2. 字母不区分大小写
一种算法就是,将原字符串剔除所有非字母数字字符,插入到一个新的字符串空间,然后基于新字符串,用2个指针法做判断。算法实现简单,不需额外考虑全空格字符串,但是占用额外空间。
另一种算法是,用2个指针指向字符串两头,当遇到非字母数字字符时跳过,然后做处理。对于全空格字符串,通过判断左指针是否会到达字符串尾部。,优点是不占用额外空间,时间复杂度上也优于第一种(只需遍历一次数组)。
算法 1 实现
class Solution { public: bool isPalindrome(string s) { string s2; int i = -1; while (++i < s.size()) { if ((s[i] < 'A' || s[i] > 'Z') && (s[i] < 'a' || s[i] > 'z') && (s[i] < '0' || s[i] > '9')) continue; else s2 += s[i]; } i = -1; int j = s2.size(); if (j == 0) return true; int interval = 'a' - 'A'; while (++i <= --j) { if (!(s2[i] == s2[j] || s2[i]+interval == s2[j] || s2[i]-interval == s2[j])) return false; } return true; } };
算法 2 实现
class Solution { public: bool isPalindrome(string s) { if (s.size() == 0) return true; int i = -1; int j = s.size(); int interval = 'a' - 'A'; while (++i <= --j) { while ((i < j) && (s[i] < 'A' || s[i] > 'Z') && (s[i] < 'a' || s[i] > 'z') && (s[i] < '0' || s[i] > '9')) i++; while ((i < j) && (s[j] < 'A' || s[j] > 'Z') && (s[j] < 'a' || s[j] > 'z') && (s[j] < '0' || s[j] > '9')) j--; // 全空格字符串 if (i == s.size()-1) return true; if (s[i] != s[j] && s[i]+interval != s[j] && s[i]-interval != s[j]) return false; } return true; } };
相关文章推荐
- POJ2352:Stars(树状数组)
- iOS评分功能、APP中打开其他应用程序
- iOS评分功能、APP中打开其他应用程序
- JSON之解析通过TouchJSON\SBJSON\JSONKit\NSJSONSeriliz...
- 大约PCA算法学习总结
- java读写数据
- CentOS 6.4下Squid代理服务器的安装与配置【转】
- Git学习总结
- 51nod 1242 斐波那契数列的第N项
- 贪心 - poj3258 River Hopscotch
- NavigationViewController
- Linux内核(一)系统启动过程
- Ubuntu10.10可用的源
- 表函数
- ServletContext与ServletConfig的详解及差异
- 第十六周阅读程序(1)
- 程序员能力矩阵 — 敢测吗?看自己在哪个档次
- PIXHAWK 软件构架
- 成员变量和局部变量
- Linux搭建Zabbix监控服务