Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd4d196d

Browse files
committed
rewrite with my len version
1 parent1e5615a commitd4d196d

File tree

1 file changed

+25
-28
lines changed

1 file changed

+25
-28
lines changed
Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,40 @@
11
publicclassSolution {
22
publicStringlongestPalindrome(Strings) {
33

4+
char[]S =s.toCharArray();
45

5-
// http://leetcode.com/2011/11/longest-palindromic-substring-part-i.html
6+
if(S.length ==0)return"";
67

7-
finalchar[]S =s.toCharArray();
8-
finalintN =S.length;
8+
boolean[][]P =newboolean[S.length][S.length];
99

10-
if(N ==0)return"";
11-
if(N ==1)returns;
12-
if(N ==2)returnS[0] ==S[1] ?s :"";
10+
intmaxi =0;
11+
intmaxlen =1;
1312

14-
boolean[][]P =newboolean[N][N];
13+
// len 1
14+
Arrays.fill(P[1 -1],true);
1515

16-
for(inti =0;i <N -1;i++){
17-
P[i][i] =true;
18-
P[i][i +1] =S[i] ==S[i +1];
19-
}
20-
21-
P[N -1][N -1] =true;
22-
23-
for(intj =2;j <N;j++){
24-
for(inti =0;i <j;i++){
25-
P[i][j] |=P[i +1][j -1] &&S[i] ==S[j];
16+
// len 2
17+
for(inti =0;i <S.length -1;i++){
18+
if(S[i] ==S[i +2 -1]){
19+
P[2 -1][i] =true;
20+
maxi =i;
21+
maxlen =2;
2622
}
2723
}
2824

29-
intmi =0;
30-
intmj =0;
31-
32-
for(inti =0;i <N;i++){
33-
for(intj =0;j <N;j++){
34-
if(P[i][j] && (j -i >mj -mi)){
35-
mi =i;
36-
mj =j;
25+
// len 3 to max
26+
for(intlen =3;len <=S.length;len++){
27+
28+
for(inti =0;i <S.length - (len -1);i++){
29+
30+
if(P[len -1 -2][i +1] &&S[i] ==S[i +len -1]){
31+
P[len -1][i] =true;
32+
maxi =i;
33+
maxlen =len;
3734
}
3835
}
39-
}
36+
}
4037

41-
returnnewString(S,mi,mj -mi +1);
38+
returns.substring(maxi,maxi +maxlen);
4239
}
43-
}
40+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp