FTPrep, 125 Valid Palindrome

来源:互联网 发布:网络消费安全的ppt 编辑:程序博客网 时间:2024/05/16 01:50

主要是会用Character类里的一些方法:

Character.isLetterOrDigit();

Character.isLetter ();

Character.isDigit();

Character.toUpperCase();

Character.toLowerCase();

这个还蛮重要的。

代码:

class Solution {    public boolean isPalindrome(String s) {        if(s.equals("")) return true;        int len = s.length();        int left=0, right=len-1;        while(left<right){            while(!Character.isLetterOrDigit(s.charAt(left))&& left<right) left++;            while(!Character.isLetterOrDigit(s.charAt(right))&& left<right) right--;            char leftChar = Character.isLetter(s.charAt(left))?Character.toLowerCase(s.charAt(left)):s.charAt(left);            char rightChar = Character.isLetter(s.charAt(right))?Character.toLowerCase(s.charAt(right)):s.charAt(right);            if(leftChar!=rightChar) return false;            left++;  // I even forget these two steps!! shame!! for every while() you should change the condition!!             right--;  // for inside while(), may include the out while condition again, if it is for the index        }        return true;    }}// lesson learned: static char Character.isLetterOrDigit(char a), is the API to use! not Digits, it is Digit// TODO: for all the palindrome questions, put them together and compare. The question I can think of: palindrome numbers. Parens is somehow a palindrome question, but palindrome can be much more diversed.