Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Longest Palindromic Substring

Posted on February 3, 2018July 26, 2020 by braindenny

Longest Palindromic Substring



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #basic, #palindrome

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## https://code.dennyzhang.com/longest-palindromic-substring
## Basic Ideas: Choose one as the middle of palindromic, then expand in both directions
##              palindromic may have odd elements or even elements
##
## Complexity: Time O(n^2), Space O(1)
class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        length = len(s)
        if length <= 1: return s
        maxCnt, middle = 0, -1
        # check the odd
        for i in range(0, length):
            cnt, j = 1, 1
            while i-j>=0 and i+j<=length-1:
                if s[i-j] != s[i+j]: break
                cnt += 2
                j += 1
            if cnt > maxCnt: maxCnt, middle = cnt, i

        # check the even
        for i in range(0, length-1):
            if s[i] != s[i+1]: continue
            cnt, j = 2, 1
            while i-j>=0 and i+j+1<=length-1:
                if s[i-j] != s[i+j+1]: break
                cnt += 2
                j += 1
            if cnt > maxCnt: maxCnt, middle = cnt, i

        if maxCnt %2 == 1:
            start = middle - int((maxCnt-1)/2)
        else:
            start = middle - int((maxCnt-2)/2)
        # print(maxCnt, start)
        return s[start:start+maxCnt]
linkedin
github
slack

Post Views: 9
Posted in BasicTagged #classic, #palindrome, redo

Post navigation

LeetCode: Shortest Palindrome
List All Problems By Tags

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.