Skip to content

Commit 0b2537e

Browse files
authored
Update 5. Longest Palindromic Substring.md
1 parent 244a2f8 commit 0b2537e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

001-100/5. Longest Palindromic Substring.md

+35
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,38 @@ var expandAroundCenter = function (s, left, right) {
6565

6666
* Time complexity : O(n^2).
6767
* Space complexity : O(1).
68+
69+
70+
```js
71+
/**
72+
* @param {string} s
73+
* @return {string}
74+
*/
75+
var longestPalindrome = function(s) {
76+
let startIndex = 0;
77+
let maxLength = 1;
78+
79+
function expandAroundCenter(left, right) {
80+
while (left >=0 && right < s.length && s[left] === s[right]) {
81+
const currentPalLength = right - left + 1;
82+
if (currentPalLength > maxLength) {
83+
maxLength = currentPalLength;
84+
startIndex = left;
85+
}
86+
left -= 1;
87+
right += 1;
88+
}
89+
}
90+
91+
for (let i = 0; i < s.length; i++) {
92+
expandAroundCenter(i-1, i+1);
93+
expandAroundCenter(i, i+1);
94+
}
95+
96+
return s.slice(startIndex, startIndex + maxLength)
97+
};
98+
```
99+
**Complexity:**
100+
101+
* Time complexity : O(n^2).
102+
* Space complexity : O(1).

0 commit comments

Comments
 (0)