leetcode | Valid Palindrome
来源:互联网 发布:嗨森矩阵 编辑:程序博客网 时间:2024/05/12 10:03
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.
解析
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; }};
- [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
- 程序员能力矩阵 — 敢测吗?看自己在哪个档次
- .net 流——使用流进行文件复制
- POJ2352:Stars(树状数组)
- java读写数据
- JSON之解析通过TouchJSON\SBJSON\JSONKit\NSJSONSeriliz...
- leetcode | Valid Palindrome
- 学生信管数据库
- 体系结构复习3——数据级并行
- 使用Spring MVC 4构建Restful服务 搭建Spring MVC 4开发环境八步走
- 黑马程序员_JAVA的构造方法
- 第15周项目1-用二进制文件处理学生成绩
- mac 递归删除文件路径 find . -name ._*|xargs rm -rf
- UITabBarController
- java大型企业级互联网框架平台 SpringMVC Mybatis Shiro Bootstrap