diff --git a/README.md b/README.md index 2bf93af3..cf1cc31d 100644 --- a/README.md +++ b/README.md @@ -557,7 +557,7 @@ LeetCode |8|[String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/)| [C++](./algorithms/cpp/stringToIntegerAtoi/stringToIntegerAtoi.cpp)|Easy| |7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/)| [C++](./algorithms/cpp/reverseInteger/reverseInteger.cpp)|Easy| |6|[ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)| [C++](./algorithms/cpp/zigZagConversion/zigZagConversion.cpp)|Easy| -|5|[Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)| [C++](./algorithms/cpp/longestPalindromicSubstring/longestPalindromicSubstring.cpp)|Medium| +|5|[Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)| [C++](./algorithms/cpp/longestPalindromicSubstring/longestPalindromicSubstring.cpp), [Javascript](./algorithms/javascript/longestPalindromicSubstring/longestPalindromicSubstring.js)|Medium| |4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)| [C++](./algorithms/cpp/medianOfTwoSortedArrays/medianOfTwoSortedArrays.cpp)|Hard| |3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| [C++](./algorithms/cpp/longestSubstringWithoutRepeatingCharacters/longestSubstringWithoutRepeatingCharacters.cpp)|Medium| |2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)| [C++](./algorithms/cpp/addTwoNumbers/addTwoNumbers.cpp)|Medium| diff --git a/algorithms/javascript/longestPalindromicSubstring/longestPalindromicSubstring.js b/algorithms/javascript/longestPalindromicSubstring/longestPalindromicSubstring.js new file mode 100644 index 00000000..74641efe --- /dev/null +++ b/algorithms/javascript/longestPalindromicSubstring/longestPalindromicSubstring.js @@ -0,0 +1,25 @@ +/** + * @param {string} s + * @return {string} + */ +var longestPalindrome = function(s) { + // ll: Left index of the longest palindrome. + // rr: Right index of the longest palindrome. + let ll = 0, rr = 0; + + // Iterate all palindromes with center indices + // [..., i, ...] or [... i, i+1, ...] + for (let i = 0; i < s.length; i++) { + for (let j of [i, i+1]) { + // console.log(j); + for (l = i, r = j; s[l] && s[l] === s[r]; l--, r++) + + // Found a new palindrome [l, ..., i, j, ..., r] + // Update the ll, rr if the newly found palindrome is longer than the + // existing one. + [ll, rr] = (r-l+1) > (rr-ll+1) ? [l, r] : [ll, rr]; + // console.log(ll + ' + ' + rr); + } + } + return s.substring(ll, rr+1); +}; \ No newline at end of file