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);
            }
        }
    }
  • 相关阅读:
    git上传本地项目
    第十一章 持有对象
    java 闭包与回调
    类名.class 类名.this 详解
    匿名内部类
    第十章 内部类
    Java简单调用Zookeeper服务
    Linux下ZooKeeper集群安装
    Linux自动化安装JDK
    linux下初步实现Keepalived+Nginx高可用
  • 原文地址:https://www.cnblogs.com/qwertwwwe/p/4480645.html
Copyright © 2011-2022 走看看