zoukankan      html  css  js  c++  java
  • LeetCode:Longest Palindromic Substring

    Longest Palindromic Substring

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

    动态规划解法 

    T(n) = O(n^2)  ,S(n) = O(n^2);

    Solution:

    public class Solution {
        private static int MAX_LENGH = 1000;
        public String longestPalindrome(String s) {
            char[] ch = s.toCharArray();
            int len = s.length();
            int maxLen = 1;
            int longestBegin = 0;
            boolean[][] table = new boolean[len+1][len+1];
            // Arrays.fill(table,false);
            
            for(int i = 0; i < len; i++){
                table[i][i] = true;
            }
            for(int i = 0; i < len-1; i++){
                if(ch[i] == ch[i+1]){
                    table[i][i+1] = true;
                    longestBegin = i;
                    maxLen = 2;
                }
            }
            for(int l = 3 ; l <= len; l++){
                for(int i = 0; i< len - l+1; i++){
                    int j = i + l -1;
                    if(ch[i] == ch[j] && table[i+1][j-1]){
                        table[i][j] = true;
                        maxLen = l;
                        longestBegin = i;
                    }
                }
            }
            return s.substring(longestBegin,longestBegin + maxLen);
        }
    }

    O(n) 线性时间复杂度算法

    极其酷炫掉渣天的方法

    http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html

  • 相关阅读:
    xp 安装 win7 64
    局域网内传输文件速度慢
    安全和共享设置
    vs2005无法启动
    dos快速通道
    xp 共享 guest
    Java菜题
    Java序列化总结(最全)
    Bitset改进你的程序质量
    Java反射方法总结
  • 原文地址:https://www.cnblogs.com/yeek/p/3813805.html
Copyright © 2011-2022 走看看