leetcode 125 Valid Palindrome
来源:互联网 发布:男女就业比例数据图片 编辑:程序博客网 时间:2024/05/20 07:35
讲道理,连着做了两个palindrome的题目,挺崩溃的。上一个题目是9题,求整数是否是palindrome,但是没有说不算负数。。。所以第一次提交的时候,还对负数进行了取绝对值之后的判断。同样,在这道题目中,求string是否是Palindrome,开始每一次提交都会有错,原因是没有考虑字符串中存在数字的情况。不知道是题目表述的不清楚,还是自己脑回路清奇。
啰嗦了这么多,下面进入正题。
1. 题目分析
题目描述: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.
题目含义:不多赘述,就是判断一个string是否是Palindrome,还给举例证明了。人性化的是,在Note中题目指出了将空串定义为有效的Palindrome。
题目分析:思路比较简单。就是首先对string进行提纯处理,去掉标点符号;然后将预处理后的string中的字母转换成同一形式,均大写或者均小写;然后使用二分法的方式一次对首尾进行对称判断。这道题目比9题容易的地方在于,string可以用指针,不需要对string进行截断处理。
2.题目解答–cpp
class Solution {public: bool isPalindrome(string s) { // 定义一个新串,用于存储格式化后的s string newstr; // exceptional case if (s.size() == 0) { return true; } // erase the punctuation and all upper to lower for (int i = 0; i < s.size(); i++) { int val = int(s[i]); if (val >= 65 && val <= 90) { newstr += s[i]; } else if (val >= 97 && val <= 122) { newstr += (s[i]-32); } else if (val >= 48 && val <= 57) { newstr += s[i]; } } // judge true or not int len = newstr.size(); int front = 0; int end = len - 1; while(front < end) { if (newstr[front] == newstr[end]) { front++; end--; } else { return false; } } return true; }};
3. 心得体会
string中可以直接使用toupper()和tolower()方法进行大小写的转换。一开始还自己通过asii进行转换,有点蠢。
编程是个细心活儿,需要考虑到各种可能出现的情况,并且要对细节考虑的十分仔细。虽然很简单,但是还是在文章开始处提到的问题浪费了很多调试时间。。学艺不精。。我自己的代码往往都特别长,后期需要提高代码的效率和空间利用率。
- LeetCode 125: Valid Palindrome
- LeetCode 125 Valid Palindrome
- LeetCode: Valid Palindrome [125]
- leetcode 125-Valid Palindrome
- [leetcode 125] Valid Palindrome
- leetCode #125 Valid Palindrome
- [LeetCode 125] Valid Palindrome
- LeetCode 125 Valid Palindrome
- leetcode-125 Valid Palindrome
- leetcode || 125、Valid Palindrome
- LeetCode---(125) Valid Palindrome
- Leetcode[125]-Valid Palindrome
- leetcode[125]:Valid Palindrome
- Leetcode# 125 Valid Palindrome
- leetcode 125: Valid Palindrome
- leetcode: (125) Valid Palindrome
- [Leetcode]#125 Valid Palindrome
- LeetCode 125 Valid Palindrome
- 【Redis进阶】Redis哨兵机制
- jvm程序计数器
- vs code快速写代码
- 利用花生壳将内网IP映射出去访问本地Web项目。
- mac下vi指令
- leetcode 125 Valid Palindrome
- MySql与Java的时间类型
- 搭建NDK环境
- Linux命令系列---route
- linux常用命令
- caffe练习实例(4)——caffe实现caltech101数据集图像分类
- FrameLayout帧布局初识
- hibernate笔记10 hibernate关联关系2
- Android View的getLeft, getRight, getTop, getBottom