码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Palindromic Substring

时间:2015-05-06 01:09:48      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

原理参考: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);
        }
    }
}

 

Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/seeit/p/4480645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!