zoukankan      html  css  js  c++  java
  • 5. 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.

    Example:

    Input: "babad"
    
    Output: "bab"
    
    Note: "aba" is also a valid answer.
    

    Example:

    Input: "cbbd"
    
    Output: "bb"

    链接:https://leetcode.com/problems/longest-palindromic-substring/#/description

    4/4/2017

    注意的问题(不包括算法本身):

    1. p的类型是int[]不是char[]

    2. 第7行循环退出条件是最后一个#,所以长度是t.length - 1。循环中$,@都是不在循环体的

    3. t的长度是s.length() * 2 + 3,不是s.length() * 2 + 1,并且主要不要遗漏开头结尾的$,@,以及最后一个#

    4. 第9行与princeton的算法判断条件略有不同,但是为什么不同还没有考虑

    5. 返回是substring,所以不但要记录最大值,更重要的是最大palindrome的位置

     1 public class Solution {
     2     public String longestPalindrome(String s) {
     3         char[] t = preprocess(s);
     4         int[] p = new int[t.length];
     5         int center = 0, right = 0, mirror;
     6 
     7         for (int i = 1; i < t.length - 1; i++) {
     8             mirror = 2 * center - i;
     9             if (mirror > 0) {
    10                 if (p[mirror] < right - i) p[i] = p[mirror];
    11                 else p[i] = right - i;
    12             }
    13             while (t[i + (1 + p[i])] == t[i - (1 + p[i])]) p[i]++;
    14             if (i + p[i] > right) {
    15                 center = i;
    16                 right = i + p[i];
    17             }
    18         }
    19 
    20         int maxCount = 0, start = 0;
    21         for (int i = 0; i < p.length; i++) {
    22             if (p[i] > maxCount) {
    23                 maxCount = p[i];
    24                 start = i - maxCount;
    25             }
    26         }
    27         char[] ret = new char[maxCount];
    28         for (int i = 0; i < maxCount; i++) {
    29             ret[i] = t[start + 1 + 2 * i];
    30         }
    31         return new String(ret);
    32     }
    33     private char[] preprocess(String s) {
    34         char[] t = new char[2 * s.length() + 3];
    35         t[0] = '$';
    36         t[2 * s.length() + 2] = '@';
    37         for (int i = 0; i < s.length(); i++) {
    38             t[2 * i + 1] = '#';
    39             t[2 * i + 2] = s.charAt(i);
    40         }
    41         t[2 * s.length() + 1] = '#';
    42         return t;
    43     }
    44 }

    算法理解:

    待我补上

    时间复杂度:

    https://en.wikipedia.org/wiki/Longest_palindromic_substring

  • 相关阅读:
    防止头文件的重复包含问题
    git常用命令
    redis
    linux常用操作
    数据库安装
    mysql修改表结构
    mysql 忘记root密码及授权访问
    mysql连表查询
    mysql 存取ip方法
    php批量修改表结构
  • 原文地址:https://www.cnblogs.com/panini/p/6666958.html
Copyright © 2011-2022 走看看