Journal Archive

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
	// simple case
    if (s.length < 2) return s;
    let result = "";
    
	// helper function
    const findPalindrome = (s, pos1, pos2) => {
        while (pos1 >= 0 && pos2 < s.length && s[pos1] === s[pos2]) {
            pos1--;
            pos2++;
        }
        return s.slice(pos1 + 1, pos2);
    }
    
    for (let i = 0; i < s.length; i++) {
        const oddPalindrome = findPalindrome(s, i, i);
        const evenPalindrome = findPalindrome(s, i, i + 1);
		// update longest palindromic string
        result = result.length > oddPalindrome.length? result: oddPalindrome;
        result = result.length > evenPalindrome.length? result: evenPalindrome;
    }
    
    return result;
};

Day 37: Solving one of LeetCode problems

5. Longest Palindromic Substring Difficulty - Medium

Given a string s, return the longest palindromic substring in s.

 

Example 1:

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
		

Example 2:

Input: s = "cbbd"
Output: "bb"