【LeetCode】之Valid Palindrome
2015-09-05 21:25
459 查看
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.因为不考虑字母的大小写,所以将字符串统一转换为小写;
2.然后定义两个指针,指向字符串的头和尾;
3.然后开始判断头和尾的字符,分两种情况:
(1)头和尾的字符不相同,直接返回false;
(2)头和尾相同或者头和尾不是字母和数字,则头的指针往后走,尾的指针往前走,知道他们会合,跳出循环,返回true。
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.因为不考虑字母的大小写,所以将字符串统一转换为小写;
2.然后定义两个指针,指向字符串的头和尾;
3.然后开始判断头和尾的字符,分两种情况:
(1)头和尾的字符不相同,直接返回false;
(2)头和尾相同或者头和尾不是字母和数字,则头的指针往后走,尾的指针往前走,知道他们会合,跳出循环,返回true。
class Solution { public: bool isPalindrome(string s) { transform(s.begin(),s.end(),s.begin(),::tolower);//将大写字母转换为小写 auto left = s.begin(); auto right = prev(s.end()); while(left<right){ if(!::isalnum(*left)) left++; else if(!::isalnum(*right)) right--; else if(*left != *right) return false; else{ left++; right--; } } return true; } };
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- android上改变listView的选中颜色
- String.intern
- Prototype源码浅析 String部分(二)
- Ruby中的String对象学习笔记
- PostgreSQL ERROR: invalid escape string 解决办法
- 浅谈C++中的string 类型占几个字节
- 标准C++类string的Copy-On-Write技术
- C++实现string存取二进制数据的方法
- C#中string和StingBuilder内存中的区别实例分析
- PHP STRING 陷阱原理说明
- c#中 String和string的区别介绍
- C#实现的图片、string相互转换类分享
- asp.net String.IsNullOrEmpty 方法
- JavaScript中字符串(string)转json的2种方法
- C#中string用法实例详解
- C#中的DataSet、string、DataTable、对象转换成Json的实现代码
- JavaScript中的object转换成number或string规则介绍