LeetCode - 125. Valid Palindrome

題目:

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.


思路與步驟:

首先理解題目要求:通過測試樣例得知,輸入的字符串只比較大小寫字母和0-9,並且忽略大小寫。於是有兩種思路

思路1:

先將元字符串中的有效字符提取出來,並且將大寫轉化爲小寫存入一個List中,然後對List中的各個元素依次比較。

思路2:

設兩個指針(在Java中也就是兩個下標值),無效字符直接跳過,有效字符轉化爲小寫後比較。這樣不需要先將元字符存入List 而一遍進行。

具體方法也有以下幾種:

1. 在判斷有效字符時有兩種方法,第一種是分別判斷大寫字母、小寫字母、0-9數字;另一種是用 Character.isLetterOrDigit(c)直接判斷。然後在用 Character.toLowerCase(c)) 全部轉換成小寫。

2. 在思路1中,存入List 之後可以依次首尾比較,也可以直接用 Collections.reverse(list2) 方法,但這裏要注意的是,

初始化 list2 的時候不能 List<Character> list2 = list;  而要List<Character> list2 = new ArrayList<Character>(list);


程序實現:

思路1:

方法1

public class Solution {
    public boolean isPalindrome(String s) {
        List<Character> list = new ArrayList<Character>();
        //method 1-1: faster
        for(char c: s.toCharArray()){
            if(('0'<=c && c<='9'))    list.add(c);
            else if('a'<=c && c<='z')    list.add(c);
            else if(('A'<=c && c<='Z'))    list.add(Character.toLowerCase(c));
        }
        //for(char c: s.toCharArray())    if(Character.isLetterOrDigit(c))    list.add(Character.toLowerCase(c));
        if(list.size()==0 || list.size()==1) return true;
        int i=0, j=list.size()-1;
        while (i<j-1 && list.get(i++)==list.get(j--));
        if((i==j-1 && list.get(i)==list.get(j)) || (i==j && list.get(i-1)==list.get(j+1))) return true;
        else return false;
    }
}

方法2

public class Solution {
    public boolean isPalindrome(String s) {
        List<Character> list = new ArrayList<Character>();
        for(char c: s.toCharArray()){
            if(('0'<=c && c<='9'))    list.add(c);
            else if('a'<=c && c<='z')    list.add(c);
            else if(('A'<=c && c<='Z'))    list.add(Character.toLowerCase(c));
        }
        //for(char c: s.toCharArray())    if(Character.isLetterOrDigit(c))    list.add(Character.toLowerCase(c));
        List<Character> list2 = new ArrayList<Character>(list);
        Collections.reverse(list2);
        return list.equals(list2);
    }
}

思路2:

public class Solution {
    public boolean isPalindrome(String s) {
        //Do not store in a list first.
        if(s.length()==0) return true;
        int i=0, j=s.length()-1;
        while (i<=j){
            if(!Character.isLetterOrDigit(s.charAt(i))) i++;
            else if(!Character.isLetterOrDigit(s.charAt(j))) j--;
            else{
                if(Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j)))    return false;
                else{
                    i++;
                    j--;
                }
            }
        }
        return true;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章