File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ package LeetCode .String .HuiWen .Solution2 ;
2+
3+ public class Solution {
4+ public String longestPalindrome (String s ) {
5+ //判断所给字符串是否为空串或者只有一个字符,如果是直接返回该字符串
6+ if (s .equals ("" )||s .length ()==1 )
7+ return s ;
8+ //创建s.length()*s.length()]的二维数组
9+ int [][] dp = new int [s .length ()][s .length ()];
10+ //创建字符数组,并将所给字符串转为字符数组存储在该数组中
11+ char [] num = s .toCharArray ();
12+ int start = 0 ;
13+ int maxLen = 1 ;//最长回文串长度
14+ //i表示正在访问的字符
15+ for (int i =0 ;i <s .length ();i ++){
16+ dp [i ][i ] = 1 ;//将二位数组初始化,所有元素都为1
17+ //如果当前正在访问的字符不是字符串的最后一个字符,并且该字符和字符串的下一个字符相等
18+ //即该子串回文串只有两个相等的字符
19+ if (i +1 <s .length () && num [i ] == num [i +1 ]) {
20+ dp [i ][i +1 ] = 1 ;
21+ start = i ;
22+ maxLen = 2 ;
23+ }
24+ }
25+ // 必须先把相同字母的回文串去除,然后把len从2开始计算
26+ for (int len =2 ;len <num .length ;len ++)
27+ {
28+ for (int i =0 ;i <num .length ;i ++)
29+ {
30+ if (i + len < num .length && num [i ] == num [i + len ]) {
31+ dp [i ][i + len ] = dp [i + 1 ][i + len - 1 ];//验证dp[i][i+len]是回文串
32+ if (dp [i ][i + len ] ==1 && len + 1 > maxLen ) {//记录下最长回文串的起始位置和长度
33+ maxLen = len + 1 ;
34+ start = i ;
35+ }
36+ }
37+
38+ }
39+ }
40+ return new String (num ,start ,maxLen );
41+ }
42+ }
Original file line number Diff line number Diff line change 1+ package LeetCode .String .HuiWen .Solution2 ;
2+
3+ public class Test {
4+ public static void main (String [] args ) {
5+ Solution sol = new Solution ();
6+ System .out .println (sol .longestPalindrome ("abcabcbb" ));
7+ }
8+ }
You can’t perform that action at this time.
0 commit comments