33import org .junit .Test ;
44
55/**
6+ * 官方解法:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zui-chang-hui-wen-zi-chuan-by-leetcode-solution/
7+ * https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zhong-xin-kuo-san-dong-tai-gui-hua-by-liweiwei1419/
68 * 5. 最长回文子串
79 * 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
810 * 示例 1:
@@ -26,9 +28,9 @@ public class Solution {
2628 *
2729 * @param s
2830 * @return x 表示增量,子串长度,
29- * 状态转移方程:dp[i][j]表示从i到j的字符串 表示字符串 s 的第 i 到 j 个字母组成的串
31+ * 状态转移方程:dp[i][j]表示字符串 s 的第 i 到 j 个字母组成的串是否是回文串
3032 */
31- public String longestPalindrome1 (String s ) {
33+ public String longestPalindrome (String s ) {
3234 if (s == null || s .length () < 2 ) {
3335 return s ;
3436 }
@@ -37,19 +39,23 @@ public String longestPalindrome1(String s) {
3739 String ans = "" ;
3840 boolean [][] dp = new boolean [n ][n ];
3941 for (int x = 0 ; x < n ; x ++) {
40- for (int i = 0 ; i + x < n ; i ++) {
42+ for (int i = 0 ; i + x < n ; i ++) { //x 表示增量,子串长度,
4143 int j = i + x ;
42- if (x == 0 ) {
44+ if (x == 0 ) { //增量是0
4345 dp [i ][j ] = true ;
44- } else if (x == 1 ) {
46+ } else if (x == 1 ) { //增量是1,只有两个字符
4547 dp [i ][j ] = (s .charAt (i ) == s .charAt (j ));
4648 } else {
47- dp [i ][j ] = (dp [i + 1 ][j - 1 ] && s .charAt (i ) == s .charAt (j ));
49+ dp [i ][j ] = (dp [i + 1 ][j - 1 ] && s .charAt (i ) == s .charAt (j )); // 判断c aba c是否是回文串,需判断aba是否是回文串以及左右两边的字符是否相等
4850 }
4951
50- if (dp [i ][j ] && x + 1 > ans .length ()) {
51- ans = s .substring (i , i + x + 1 );
52+ if (dp [i ][j ] && j - i + 1 > ans .length ()) { // i到j组成的串是回文串,并且回文串的长度是否大于之前的回文串长度
53+ ans = s .substring (i , j + 1 );
5254 }
55+
56+ //if (dp[i][j] && x + 1 > ans.length()) { // 可以将j-i+1替换成x+1,i+x+1替换成j+1,都表示回文串的长度
57+ // ans = s.substring(i, i + x + 1);
58+ //}
5359 }
5460 }
5561 return ans ;
@@ -89,9 +95,9 @@ private int expandAroundCenter(String s, int left, int right) {
8995 @ Test
9096 public void test () {
9197 System .out .println ("123456" .substring (0 , 3 ));
92- System .out .println (longestPalindrome1 ("dcacdefd" ));
93- System .out .println (longestPalindrome1 ("babad" ));
94- System .out .println (longestPalindrome1 ("cbbd" ));
98+ System .out .println (longestPalindrome ("dcacdefd" ));
99+ System .out .println (longestPalindrome ("babad" ));
100+ System .out .println (longestPalindrome ("cbbd" ));
95101 }
96102
97103}
0 commit comments