leetcode 125 Vaild Palindrome
2015-10-24 14:14
453 查看
验证是否为回文
题目要求:给出一个字符串,验证其是否为回文(忽略非字母字符并忽略大小写)
tags:String, Two Pointer
一般验证是否为回文使用two pointer,比较头尾指针是否相同,做该题时还需要忽略非字母字符,并将字符都转换为小写(或大写)再进行比较。
还有另一种取巧的办法:使用正则表达式,去掉其中非字幕的字符,并将字符串全部转为小写(或大写),再翻转,比较两个字符串是否相同。这些都可以用java自带的函数来解决。
题目要求:给出一个字符串,验证其是否为回文(忽略非字母字符并忽略大小写)
tags:String, Two Pointer
一般验证是否为回文使用two pointer,比较头尾指针是否相同,做该题时还需要忽略非字母字符,并将字符都转换为小写(或大写)再进行比较。
public boolean isPalindrome(String s) { int head=0; int tail=s.length()-1; while(head<tail){ char h = Character.toLowerCase(s.charAt(head)); char t = Character.toLowerCase(s.charAt(tail)); if(!Character.isLetter(h)&&!Character.isDigit(h)){ head++; continue; } if(!Character.isLetter(t)&&!Character.isDigit(t)){ tail--; continue; } if(h!=t){ return false; } tail--; head++; } <span style="white-space:pre"> </span>return true; }
还有另一种取巧的办法:使用正则表达式,去掉其中非字幕的字符,并将字符串全部转为小写(或大写),再翻转,比较两个字符串是否相同。这些都可以用java自带的函数来解决。
public boolean isPalindrome2(String s) { <span style="white-space:pre"> </span>String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase(); String rev = new StringBuffer(actual).reverse().toString(); return actual.equals(rev); }
相关文章推荐
- LeetCodeOJ_205_Submission Details
- Contains Duplicate II - LeetCode
- leetcode先刷_Climbing Stairs
- LeetCode——Container With Most Water
- 我读Fine-Grained Change Detection of Misaligned Scenes with Varied Illuminations
- hdoj 2473 Junk-Mail Filter
- UVALive 7147 World Cup(2014 Regionals 2014 :: Asia - ShangHai)
- paint类,path用法
- Airbnb如何冲破租赁平台两大弊端的封锁而获得成功
- Linux系统wait()和waitpid()函数
- 第 22 章 Master-Detail 用户界面
- HDU 5029 Relief grain (树链剖分 + 线段树)
- [PAT (Advanced Level) ]1014.Waiting in Line 解题文档
- Mahout分类算法学习之实现Naive Bayes分类示例
- Light OJ 1021 - Painful Bases(状态压缩DP)
- UVA-11374 Airport Express (dijkstra+枚举)
- aix 11.2.0.4的 rac 中“asm 磁盘组normal冗余模式 + cdp镜像存储”的方式 存在的问题。
- Exception in thread "main" org.I0Itec.zkclient.exception.ZkTimeoutException: Unable to co
- 问题— 修改AFNetworking源文件可接收text/plain的方法
- org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update