• 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);
            }
        }
    }
  • 相关阅读:
    流形学习(Mainfold Learning)
    陈皓的博客
    背包九讲
    阮一峰的个人网站
    PyTorch教程【六】Transforms的使用
    PyCharm设置代码提示忽略大小写
    PyTorch教程【五】TensoBoard的使用
    pip 换源
    PyCharm常用快捷键
    JAVA基础篇—HashMap
  • 原文地址:https://www.cnblogs.com/qwertwwwe/p/4480645.html
Copyright © 2020-2023  润新知