判斷一個字符串裏最長迴文的長度

 public static int gatMaxlenOfHuiwen(String s){

        if(s==null || s.length()<=0){
            return 0;
        }

        int maxLen = 1;
        char[] generatedChars = getInsertedArray(s);
        for(int i = 2; i<generatedChars.length-1-2; i++){
            int tmpLen = 1;
            while(generatedChars[i-tmpLen] == generatedChars[i+tmpLen]){
                tmpLen++;
            }

            maxLen = getMax(maxLen, tmpLen-1);
        }


       return maxLen;
    }

    // #a#b#c

    public static char[] getInsertedArray(String s){
        if(s==null || s.isEmpty()){
            return null;
        }

        char[] temp = new char[2*s.length()+3];

        temp[0] = '$';
        temp[1] = '#';
        char[] chars = s.toCharArray();
        for(int i=0; i<s.length(); i++){
             temp[i*2+2] = chars[i];
             temp[i*2+2+1] = '#';
        }

        temp[2*s.length()+2] = '\0';
        return temp;
    }

    public static int getMax(int value1, int value2) {
        if (value1 > value2) {
            return value1;
        }

        return value2;
    }

注意這裏數組前後端有個$ '\0' 這樣就不用判斷數組是否到頭尾了。

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