-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestpalindromicsubstring.js
More file actions
94 lines (79 loc) · 2.09 KB
/
longestpalindromicsubstring.js
File metadata and controls
94 lines (79 loc) · 2.09 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
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Longest Palindromic Substring
// Given a string s, return the longest palindromic substring in s.
// Example 1:
// Input: s = "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: s = "cbbd"
// Output: "bb"
// Example 3:
// Input: s = "a"
// Output: "a"
// Example 4:
// Input: s = "ac"
// Output: "a"
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (s) {
// check for single characters
if (s.length == 1) return s;
// check for two characters
if (s.length == 2) {
if (s[0] == s[1]) {
return s
} else {
return s[0]
}
}
// check if whole string is a palindrome
if (s == s.split("").reverse().join("")) {
return s;
}
// check for substring palindrome
/**
logic:
A palindrome must start and end with same character
Hence, finding all possible words beginning and ending with same character
Next if any computed word is a palindrome then that's the result
ex:- xaabacxcabaaxcabaax
char: x
xaabacx
xaabacxcabaax
xaabacxcabaaxcabaax
char a
acxca
acxcaba
acxcabaa
acxcabaaxca
acxcabaaxcaba
....
char a
char b
char a
char c
....
*/
let subStr = "";
let left = 0;
while (left < s.length) {
let char = s[left];
let idxs = [];
s.split("").filter((chr, index) => {
if (chr == char && index > left) {
idxs.push(index);
let matchChar = s.slice(left, index + 1);
if (matchChar.length > subStr.length) {
let inv = matchChar.split("").reverse().join("")
if (matchChar == inv) {
subStr = matchChar;
}
}
}
});
left++;
}
return subStr.length > 1 ? subStr : s[0]
};