Skip to content

Commit 62fe628

Browse files
Longest Palindromic Substring (ignacio-chiazzo#24)
1 parent 8bc6588 commit 62fe628

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
https://leetcode.com/problems/longest-palindromic-substring/description/
3+
4+
Longest Palindromic Substring
5+
6+
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
7+
8+
Example 1:
9+
10+
Input: "babad"
11+
Output: "bab"
12+
Note: "aba" is also a valid answer.
13+
Example 2:
14+
15+
Input: "cbbd"
16+
Output: "bb"
17+
*/
18+
19+
20+
/**
21+
* @param {string} s
22+
* @return {string}
23+
*/
24+
var longestPalindrome = function(str) {
25+
if(str.length == 0)
26+
return "";
27+
28+
var maxPal = 1;
29+
var posPalStart = 0;
30+
var currentPalStart = 0;
31+
32+
for(var i = 1; i < str.length; i++) {
33+
if(str.charAt(i - 1) == str.charAt(i)) {
34+
currentPalStart = i - 1;
35+
var currentPal = 2;
36+
var iter = 1;
37+
while(i - iter - 1 >= 0 && i + iter < str.length &&
38+
str.charAt(i - iter - 1) == str.charAt(i + iter)) {
39+
currentPalStart = i - iter - 1;
40+
iter++;
41+
currentPal += 2;
42+
}
43+
}
44+
if(currentPal > maxPal) {
45+
maxPal = currentPal;
46+
posPalStart = currentPalStart;
47+
}
48+
}
49+
50+
for(var i = 1; i < str.length - 1; i++) {
51+
if(str.charAt(i - 1) == str.charAt(i + 1)) {
52+
currentPal = 1;
53+
var iter = 1;
54+
while(i - iter >= 0 && i + iter < str.length &&
55+
str.charAt(i - iter) == str.charAt(i + iter)) {
56+
currentPalStart = i - iter;
57+
iter++;
58+
currentPal += 2;
59+
}
60+
}
61+
if(currentPal > maxPal) {
62+
maxPal = currentPal;
63+
posPalStart = currentPalStart;
64+
}
65+
}
66+
67+
return str.slice(posPalStart, posPalStart + maxPal);
68+
}
69+
70+
var main = function() {
71+
console.log(longestPalindrome("pabcdcbte"));
72+
console.log(longestPalindrome("bb"));
73+
console.log(longestPalindrome(""));
74+
console.log(longestPalindrome("bbb"));
75+
console.log(longestPalindrome("bbbb"));
76+
console.log(longestPalindrome("ptabbbbat"));
77+
}
78+
79+
module.exports.main = main

0 commit comments

Comments
 (0)