[LeetCode 125] Valid Palindrome
2016-07-29 00:00
295 查看
https://leetcode.com/problems/valid-palindrome/
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
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.
这题比较常规,思路也很简单,就是 two pointers。一根指针指向字符串的开始位置,另一根指针指向字符串的结束位置。当中使用 while 循环忽略掉 non-alphanumeric 字符即可。来看下面代码:
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.
这题比较常规,思路也很简单,就是 two pointers。一根指针指向字符串的开始位置,另一根指针指向字符串的结束位置。当中使用 while 循环忽略掉 non-alphanumeric 字符即可。来看下面代码:
class Solution { public: bool isPalindrome(string s) { string::const_iterator left = s.cbegin(); string::const_iterator right = s.cend() - 1; while (left < right) { // 忽略掉 non-alphanumeric 字符 while (left < right && !isalnum(*left)) { left++; } while (left < right && !isalnum(*right)) { right--; } if (tolower(*left) != tolower(*right)) { return false; } else { left++; right--; } } return true; } };
相关文章推荐
- Dynamic Programming | Set 4 (Longest Common Subsequence)
- 我的C实践(5):舍入到2的幂
- Python函数式编程指南
- SMBIOS介绍(2):结构表
- dbm数据库源代码分析(12):gdbmreorg.c、gdbmseq.c和gdbmsetopt.c
- 机器学习之正则化(Regularization)
- 王淮、龚世海谈如何打造优秀的技术团队
- Linux网络编程1——小端模式与大端模式
- C标准库源码解剖(15):数学函数库math.h, tgmath.h和complex.h
- Linux网络编程2——系统函数
- [LintCode] Longest Increasing Continuous subsequence
- 第6部分:AOP
- SQLite剖析(5):体系结构
- KMeans
- Notes for Apue —— chapter 4 Files and Directories(文件和目录)
- Linux网络编程5——使用UDP协议实现群聊
- 网络IO模型
- 我的C++实践(15):判断对象是在堆上还是在栈上
- 为什么要使用NoSQL
- Python面向对象编程指南