[LeetCode-interview algorithm classic-Java implementation] [005-Longest Palindromic Substring (Longest reply Substring)],-javapalindromic
[005-Longest Palindromic Substring (Longest echo string )]Original question
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.
Theme
Given a string S and finding out its largest substring, you can assume that the maximum length of the string is 1000, and there is a unique longest substring
Solutions
Dynamic Programming,
Assume that the value of dp [I] [j] is true, which indicates that the substring consisting of subscripts from I to j in string s is a return string. Then we can launch:
Dp [I] [j] = dp [I + 1] [j-1] & s [I] = s [j].
This is a general situation. Because I + 1 and j-1 are required, it is possible that I + 1 = j-1, I + 1 = (j-1)-1, therefore, the above formula can be applied only when the benchmark is obtained:
A. I + 1 = j-1, that is, when the return length is 1, dp [I] [I] = true;
B. I + 1 = (j-1)-1, that is, when the return length is 2, dp [I] [I + 1] = (s [I] = s [I + 1]).
With the above analysis, you can write the code. Note that dynamic planning requires additional O (n ^ 2) space.
Code Implementation
Public class Solution {/*** 005-Longest Palindromic Substring (Longest echo Substring) ** @ param s the input String * @ return the longest echo substring */public String longestPalindrome (String s) {if (s = null | s. length () <2) {return s;} int maxLength = 0; String longest = null; int length = s. length (); boolean [] [] table = new boolean [length] [length]; // a single character is a forward for (int I = 0; I <length; I ++) {table [I] [I] = true; longest = s. substring (I, I + 1); maxLength = 1;} // determines whether two characters are in the for (int I = 0; I <length-1; I ++) {if (s. charAt (I) = s. charAt (I + 1) {table [I] [I + 1] = true; longest = s. substring (I, I + 2); maxLength = 2 ;}// determine whether the substring with a length greater than 2 is a return string for (int len = 3; len <= length; len ++) {for (int I = 0, j; (j = I + len-1) <= length-1; I ++) {if (s. charAt (I) = s. charAt (j) {table [I] [j] = table [I + 1] [j-1]; if (table [I] [j] & maxLength <len) {longest = s. substring (I, j + 1); maxLength = len ;}} else {table [I] [j] = false ;}} return longest ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the source for reprinting [http://blog.csdn.net/derrantcm/article/details/46922011]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.