#415 Valid Palindrome
来源:互联网 发布:博客源码 编辑:程序博客网 时间:2024/06/05 19:16
题目描述:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Notice
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.
Example
"A man, a plan, a canal: Panama"
is a palindrome.
"race a car"
is not a palindrome.
Challenge
题目思路:O(n) time without extra memory.
这题还是two pointers的想法,分别设一个l在string的最左,一个r在string的最右,然后慢慢向对移动,遇到不是数字或者字母的就跳过,出循环的条件是l<r,return false的条件是所指的对象不相同。
Mycode(AC = 34ms):
class Solution {public: /** * @param s A string * @return Whether the string is a valid palindrome */ bool isPalindrome(string& s) { // Write your code here // two pointers to check whether s[l] == s[r] int l = 0, r = s.length() - 1; while (l < r) { while (l < r && !isAlphaNum(tolower(s[l]))) { l++; } while (l < r && !isAlphaNum(tolower(s[r]))) { r--; } if (l >= r) break; if (tolower(s[l]) != tolower(s[r])) return false; l++; r--; } return true; } // return true if ch is alphanumerical bool isAlphaNum(char ch) { return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'); }};
0 0
- #415 Valid Palindrome
- #415 Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- valid palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- Valid Palindrome
- studio编译时错误提示:Plugin is too old, please update to a more recent,导致无法运行
- 免安装版mysql(ZIP解压缩版)
- 网易有道内推笔试题
- HTML中jquery控制button按钮可点击、不可点击
- springmvc form表单标签使用
- #415 Valid Palindrome
- UITableView
- $ajax发送请求数据库数据不动
- Spring Boot 拦截器
- 二,Shiro概述(2)
- 编译编码问题
- python-netsnmp扩展(2)管理端简单功能开发
- svn: E175002: REPORT of '/xxxx-demo/!svn/vcc/default': Could not read response body: Secure connecti
- 我的WCF数据服务(二)独立