LeetCode-Valid Palindrome

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; }}

你可能感兴趣的:(LeetCode-Valid Palindrome)