diff --git a/001-100/5. Longest Palindromic Substring.md b/001-100/5. Longest Palindromic Substring.md index 621c252..ce66690 100644 --- a/001-100/5. Longest Palindromic Substring.md +++ b/001-100/5. Longest Palindromic Substring.md @@ -65,3 +65,38 @@ var expandAroundCenter = function (s, left, right) { * Time complexity : O(n^2). * Space complexity : O(1). + + +```js +/** + * @param {string} s + * @return {string} + */ +var longestPalindrome = function(s) { + let startIndex = 0; + let maxLength = 1; + + function expandAroundCenter(left, right) { + while (left >=0 && right < s.length && s[left] === s[right]) { + const currentPalLength = right - left + 1; + if (currentPalLength > maxLength) { + maxLength = currentPalLength; + startIndex = left; + } + left -= 1; + right += 1; + } + } + + for (let i = 0; i < s.length; i++) { + expandAroundCenter(i-1, i+1); + expandAroundCenter(i, i+1); + } + + return s.slice(startIndex, startIndex + maxLength) +}; +``` +**Complexity:** + +* Time complexity : O(n^2). +* Space complexity : O(1). diff --git a/101-200/125. Valid Palindrome.md b/101-200/125. Valid Palindrome.md index 4c67e40..cfed0d7 100644 --- a/101-200/125. Valid Palindrome.md +++ b/101-200/125. Valid Palindrome.md @@ -61,3 +61,34 @@ nope. * Time complexity : O(n). * Space complexity : O(n). + + +```js +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function(s) { + + s = s.toLowerCase().replace(/[\W_]/g, ''); + + let left = 0; + let right = s.length - 1; + + while (left < right) { + if (s[left] !== s[right]) { + return false + } + left++; + right--; + } + + return true; + +}; +``` + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). left and right pointers take the constant space.