-
Notifications
You must be signed in to change notification settings - Fork 91
/
Longest_Palindromic_Substring.js
74 lines (64 loc) · 1.59 KB
/
Longest_Palindromic_Substring.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Longest Palindromic Substring
https://leetcode.com/problems/longest-palindromic-substring/description/
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
*/
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (str) {
if (str.length == 0) return "";
var maxPal = 1;
var posPalStart = 0;
var currentPalStart = 0;
var iter = 1;
for (var i = 1; i < str.length; i++) {
if (str.charAt(i - 1) == str.charAt(i)) {
currentPalStart = i - 1;
var currentPal = 2;
iter = 1;
while (
i - iter - 1 >= 0 &&
i + iter < str.length &&
str.charAt(i - iter - 1) == str.charAt(i + iter)
) {
currentPalStart = i - iter - 1;
iter++;
currentPal += 2;
}
}
if (currentPal > maxPal) {
maxPal = currentPal;
posPalStart = currentPalStart;
}
}
for (i = 1; i < str.length - 1; i++) {
if (str.charAt(i - 1) == str.charAt(i + 1)) {
currentPal = 1;
iter = 1;
while (
i - iter >= 0 &&
i + iter < str.length &&
str.charAt(i - iter) == str.charAt(i + iter)
) {
currentPalStart = i - iter;
iter++;
currentPal += 2;
}
}
if (currentPal > maxPal) {
maxPal = currentPal;
posPalStart = currentPalStart;
}
}
return str.slice(posPalStart, posPalStart + maxPal);
};
module.exports.longestPalindrome = longestPalindrome;