- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromicSubstring.js
More file actions
Latest commit
48 lines (39 loc) · 1.12 KB
/
Copy pathPalindromicSubstring.js
File metadata and controls
48 lines (39 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* description :
Given a string s, return the longest
palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb" */
/* ---------------------------------------------------------- */
varlongestPalindrome=(s)=>{
letlongest='';
for(leti=0;i<s.length;i++){
// Check odd-length palindromes
letleft=i,right=i;
while(left>=0&&right<s.length&&s[left]===s[right]){
letpalindrome=s.substring(left,right+1);
if(palindrome.length>longest.length){
longest=palindrome;
}
left--;
right++;
}
// Check even-length palindromes
left=i;
right=i+1;
while(left>=0&&right<s.length&&s[left]===s[right]){
letpalindrome=s.substring(left,right+1);
if(palindrome.length>longest.length){
longest=palindrome;
}
left--;
right++;
}
}
returnlongest;
};
console.log(longestPalindrome('cbbd'))