LeetCode-Valid Palindrome
来源:互联网 发布:vs2017 连接mysql 编辑:程序博客网 时间:2024/06/06 20:33
public class Solution { public boolean isPalindrome(String s) { if ( s == null || s.length() == 0) return true; s = s.replaceAll("[^a-zA-Z0-9 ]", "").toLowerCase(); s = s.replaceAll(" ", ""); if ( s.length() == 1 || s.length() == 0) return true; int headP = 0; int tailP = s.length()-1; while (headP < tailP){ if ( s.charAt(headP) != s.charAt(tailP) ) return false; tailP --; headP ++; } return true; }}
判断是否是回文,回文就是从两头读是一样的(是这样吗???!!)
所以要两个index 一个从head 一个从tail,每个char比较一下,对称位置只要不一样就返回false。
这个题用到了许多java string的函数 非常好用
str.replaceAll("[^a-zA-Z ]", "") 将第一个argu用第二个代替,其中[^a-zA-Z]是正则表达式,表示所有不是letter的字符,还可以加上0-9,这样就去掉了所有标点,只留下letter和数字。但是并没有去掉空格,所以空格还要再去一遍。
str.toLowerCase()
public class Solution { public boolean isPalindrome(String s) { if ( s == null || s.length() == 0) return true; s = s.replaceAll("[^a-zA-Z0-9 ]", "").toLowerCase(); s = s.replaceAll(" ", ""); if ( s.length() == 1 || s.length() == 0) return true; int headP = 0; int tailP = s.length()-1; while (headP < tailP){ if ( s.charAt(headP) != s.charAt(tailP) ) return false; tailP --; headP ++; } return true; }} 0 0
- [Leetcode] Valid Palindrome
- Leetcode: Valid Palindrome
- leetcode 55: Valid Palindrome
- [LeetCode] Valid Palindrome
- 【leetcode】Valid Palindrome
- LeetCode - Valid Palindrome
- [leetcode]Valid Palindrome
- [LeetCode]Valid Palindrome
- [Leetcode]Valid Palindrome
- LeetCode-Valid Palindrome
- [leetcode] Valid Palindrome
- LeetCode 125: Valid Palindrome
- LeetCode - Valid Palindrome
- leetcode之Valid Palindrome
- LeetCode | Valid Palindrome
- [leetcode]Valid Palindrome
- 【leetcode】Valid Palindrome
- LeetCode题解:Valid Palindrome
- spoj10606 数位dp (求出现的数字,所有偶数出现奇数次,所有奇数出现偶数次)
- Flex——Array,ArrayCollection,Vector性能比较
- [算法系列之二十二]包含T全部元素的最小子窗口
- UVa #10817 Headmaster's Headache (例题9-15)
- Linux下servlet上传文件
- LeetCode-Valid Palindrome
- java 异常基础知识以及一些面试题讲解
- Gradle创建项目目录结构
- 1006. Sign In and Sign Out (25)
- 几种session存储方式
- 手游开发商Plarium谈游戏研发的2大‘秘方’
- 1007. Maximum Subsequence Sum (25)
- 1008. Elevator (20)
- (尺取法+素数打表)poj2739,Sum of Consecutive Prime Numbers