zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    }
  • 相关阅读:
    [NOIp2016] 天天爱跑步
    状压DP小拼盘
    DP × KMP
    KMP算法 详解+模板
    [NOI2014] 起床困难综合症
    [洛谷P3391] 文艺平衡树 (Splay模板)
    START
    【C】单链表的实现
    【数据结构】动态顺序表
    C语言实现扫雷程序
  • 原文地址:https://www.cnblogs.com/qwertwwwe/p/4480645.html
Copyright © 2011-2022 走看看