Longest Palindromic Substring

原理参考:http://www.douban.com/note/321468038/

 

public class Solution {
    public String longestPalindrome(String s) {
        if((s == null) || (s.length() == 0)) {
            return "";
        }
        
        int len = s.length() * 2 + 1;
        char[] str = new char[len];
        for(int i = 0; i < len; i++) {
            if(i % 2 == 0) {
                str[i] = '#';
            }else {
                str[i] = s.charAt(i / 2);
            }
        }
        
        int maxIndex = -1;
        int maxValue = -1;
        int[] mark = new int[len];
        
        for(int i = 0; i < len; i++) {
            if(i >= maxValue) {
                int length = 0;
                while((i - length - 1>= 0) && (i + length + 1< len)
                        && (str[i - length - 1] == str[i + length + 1])) {
                    length++;
                }
                mark[i] = length;
                if(i + length > maxValue) {
                    maxValue = i + length;
                    maxIndex = i;
                }
            }else {
                int mirror = 2 * maxIndex - i;
                int length = Math.min(mark[mirror], maxValue - i);
                while((i - length - 1>= 0) && (i + length + 1< len)
                        && (str[i - length - 1] == str[i + length + 1])) {
                    length++;
                }
                mark[i] = length;
                if(i + length > maxValue) {
                    maxValue = i + length;
                    maxIndex = i;
                }
            }
        }
        
        int res = 0, index = 0;
        for(int i = 0; i < len; i++) {
            int value = mark[i];
            if(res < value) {
                res = value;
                index = i;
            }
        }
        
        if(str[index] == '#') {
            return s.substring(index / 2 - res / 2, index / 2 + res / 2);
        }else {
            return s.substring(index / 2 - res / 2, index / 2 + res / 2 + 1);
        }
    }
}

 

posted @ 2015-05-05 23:17  qwertwwwe  阅读(202)  评论(0编辑  收藏  举报