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

Commit9c91f38

Browse files
committed
Next tasks
1 parentf7bd842 commit9c91f38

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import{longestPalindrome}from'./index';
2+
3+
describe('longestPalindrome',()=>{
4+
consttestCases=[
5+
{
6+
name:'Case 1',
7+
input:'babad',
8+
expected:'bab',
9+
},
10+
{
11+
name:'Case 2',
12+
input:'cbbd',
13+
expected:'bb',
14+
},
15+
{
16+
name:'Case 3',
17+
input:'aacabdkacaa',
18+
expected:'aca',
19+
},
20+
];
21+
22+
for(consttestCaseoftestCases){
23+
test(testCase.name,()=>{
24+
expect(longestPalindrome(testCase.input)).toBe(testCase.expected);
25+
});
26+
}
27+
});
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Condition of the task:
2+
// Given a string s, return the longest palindromic substring in s.
3+
4+
constprocessString=(s:string):string=>{
5+
letres='';
6+
7+
for(leti=0;i<s.length;i++){
8+
res+=`#${s[i]}`;
9+
}
10+
11+
returnres+'#';
12+
};
13+
14+
constmin=(a:number,b:number):number=>(a<b ?a :b);
15+
exportconstlongestPalindrome=(s:string):string=>{
16+
constprocessedString=processString(s);
17+
constn=processedString.length;
18+
constP=newArray(n).fill(0);
19+
letC=0,
20+
R=0;
21+
22+
for(leti=0;i<n-1;i++){
23+
constmirror=2*C-i;
24+
25+
if(i<R){
26+
P[i]=min(R-i,P[mirror]);
27+
}else{
28+
P[i]=0;
29+
}
30+
31+
while(
32+
i+1+P[i]<n&&
33+
i-1-P[i]>=0&&
34+
processedString[i+1+P[i]]===processedString[i-1-P[i]]
35+
){
36+
P[i]++;
37+
}
38+
39+
if(i+P[i]>R){
40+
C=i;
41+
R=i+P[i];
42+
}
43+
}
44+
letmaxLen=0;
45+
letcenterIndex=0;
46+
for(leti=0;i<n;i++){
47+
if(P[i]>maxLen){
48+
maxLen=P[i];
49+
centerIndex=i;
50+
}
51+
}
52+
53+
conststart=(centerIndex-maxLen)/2;
54+
constend=start+maxLen;
55+
returns.slice(start,end);
56+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp