关于LeetCode中Valid Palindrome一题的理解
来源:互联网 发布:心灵鸡汤 知乎 编辑:程序博客网 时间:2024/05/22 14:05
题目如下:
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”,这个单词的意思是“字母数字组成的”,我当时做的时候把这个单词想成了“只有字母组成的”,没有考虑到数字的情况,结果就GG了,没有一次性Accepted。好啦,其实重点在于把非字母数字字符去掉,然后注意大小写,比较的时候要不都转化成大写,要不都转化成小写,要不就提前转化为都是大写或者都是小写。注意这两点基本上也没啥问题了,代码也是简单易懂,我就不过多地解释了,直接放已Accepted的代码:
public boolean isPalindrome(String s) { s = s.toUpperCase(); int i=0; int j=s.length()-1; while(i<j){ char forword = s.charAt(i); char backword = s.charAt(j); if(forword>'Z' || forword<'0' || (forword<'A' && forword>'9')){ i++; continue; } if(backword>'Z'|| backword<'0'|| (backword<'A' && backword>'9')){ j--; continue; } if(forword == backword){ i++; j--; }else{ return false; } } return true; }然后照例要贴一个评论区代码,找了一个View数最多的,试了一下。在循环过程中将字符转化为大写或者小写要比最开始直接把整个字符串都变成大写或小写要快不少。我没那么写是因为我当时没找到这个方法(但是我知道一定有,明明就是很懒)。好了,不多说,思路几乎一模一样,代码如下:
public boolean isPalindrome(String s) { if (s.isEmpty()) { return true; } int head = 0, tail = s.length() - 1; char cHead, cTail; while(head <= tail) { cHead = s.charAt(head); cTail = s.charAt(tail); if (!Character.isLetterOrDigit(cHead)) { head++; } else if(!Character.isLetterOrDigit(cTail)) { tail--; } else { if (Character.toLowerCase(cHead) != Character.toLowerCase(cTail)) { return false; } head++; tail--; } } return true; }这次的题目还是挺简单的,哈哈。
1 0
- 关于LeetCode中Valid Palindrome一题的理解
- 关于LeetCode中Palindrome Number一题的理解
- 关于LeetCode中Palindrome Linked List一题的理解
- 关于LeetCode中Valid Anagram一题的理解
- 关于LeetCode中Valid Parentheses一题的理解
- 和大神们学习每天一题(leetcode)-Valid Palindrome
- LeetCode 154题:Valid Palindrome
- 关于Leetcode中sum of integers一题的理解
- 关于Leetcode中Same Tree一题的理解
- 关于LeetCode中Power of Two一题的理解
- 关于LeetCode中Reverse String一题的理解
- 关于LeetCode中Invert Binary Tree一题的理解
- 关于LeetCode中Reverse Integer一题的理解
- 关于LeetCode中Ransom Note一题的理解
- 关于LeetCode中Find the Difference一题的理解
- 关于LeetCode中Remove Element一题的理解
- 关于LeetCode中Symmetric Tree一题的理解
- 关于LeetCode中Longest Common Prefix一题的理解
- linux硬盘挂载
- 一些实用的正则表达式
- 【51Nod1133】不重叠的线段
- 互联网架构,如何进行容量设计
- Bulb Switcher
- 关于LeetCode中Valid Palindrome一题的理解
- 用 CSS3 画心形和搜索放大镜图标
- python loggin记录日志,traceback打印stack
- java comparator.sort 可能注意事项
- POJ 2236并查集
- Android开发不得不看的网址
- 使用PHP写出一个正则表达式,过滤网页上的所有js脚本
- QQ加好友代码 强行聊天的代码 HTML
- USB子系统