Data Structure and Algorithms
  • Introduction
  • 面经
    • 亚马逊面经
  • Sorting
    • Quick Sort
    • Merge Sort
    • Heap Sort
  • Palindrome
    • Check String Palindrom
    • Palindrome Partitioning
    • Palindrome Partitioning II
    • Longest Palindromic Substring
    • Valid Palindrome
  • Linked List
    • Remove Duplicates from Sorted List
    • Remove Duplicates from Sorted List II
    • Remove Nth Node From End of List
    • Remove Linked List Elements
    • Remove Duplicates from Unsorted List
    • Remove duplicate Circular Linked list
    • Reverse Linked List
    • Reverse Linked List II
    • Reverse Nodes in k-Group
    • Partition List
    • Insertion Sort List
    • Reorder List
    • Linked List Cycle
    • Rotate List
    • Merge k Sorted Lists
    • Copy List with Random Pointer
    • Nth to Last Node in List
    • Add Two Numbers
    • Add Two Numbers II
    • Palindrome Linked List
  • Binary Search
    • Sqrt(x)
    • Search a 2D Matrix
    • Search a 2D Matrix II
    • Search Insert Position
    • First Position of Target
    • Last Position of Target
    • Count of Smaller Number
    • Search for a Range
    • Search in a Big Sorted Array
    • First Bad Version
    • Find Minimum in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array II
    • Search in Rotated Sorted Array
    • Search in Rotated Sorted Array II
    • Find Peak Element*
    • Recover Rotated Sorted Array
    • Rotate String
    • Wood Cut
    • Total Occurrence of Target
    • Closest Number in Sorted Array
    • K Closest Number in Sorted Array
    • Maximum Number in Mountain Sequence
    • Search Insert Position *
    • Pow(x, n)
    • Divide Two Integers
  • Graph
    • Clone Graph
    • Topological Sorting
    • Permutations
    • Permutations II
    • Subsets
    • Subsets II
    • Word Ladder
    • Word Ladder II
    • N-Queens
    • N-Queens II
    • Connected Component in Undirected Graph
    • Six Degrees
    • String Permutation II
    • Letter Case Permutation
  • Data Structure
    • Min Stack
    • Implement a Queue by Two Stacks
    • Largest Rectangle in Histogram
    • Max Tree
    • Rehashing
    • LRU Cache
    • Subarray Sum
    • Anagrams
    • Longest Consecutive Sequence
    • Data Stream Median
    • Heapify
    • Ugly Number
    • Ugly Number II
  • Misc
    • PlaceHolder
    • Fibonacci
  • Array and Numbers
    • Merge Sorted Array
    • Merge Two Sorted Arrays
    • Median of two Sorted Arrays
    • Best Time to Buy and Sell Stock
    • Best Time to Buy and Sell Stock II
    • Best Time to Buy and Sell Stock III
    • Maximum Subarray
    • Maximum Subarray II
    • Maximum Subarray III
    • Minimum Subarray
    • Maximum Subarray Difference
    • Subarray Sum
    • Subarray Sum Closest
    • Two Sum
    • 3Sum
    • 3Sum Closest
    • 4Sum
    • k Sum
    • k Sum II
    • Partition Array
    • Sort Letters by Case
    • Sort Colors
    • Sort Colors II
    • Interleaving Positive and Negative Numbers
    • Spiral Matrix
    • Spiral Matrix II
    • Rotate Image
  • Dynamic Programming I
    • Triangle
    • Minimum Path Sum
    • Unique Paths
    • Unique Paths II
    • Climbing Stairs
    • Jump Game
    • Jump Game II
    • 01 Matrix
    • Longest Line of Consecutive One in Matrix
    • Shortest Path in Binary Matrix
  • Dynamic Programming II
    • Word Break
    • Longest Common Subsequence
    • Longest Common Substring
    • Edit Distance
    • Distinct Subsequences
    • Interleaving String
    • k Sum
  • Binary Tree And Divide Conquer
    • Binary Tree Preorder Traversal*
    • Binary Tree Inorder Traversal*
    • Binary Tree Postorder Traversal*
    • Maximum Depth of Binary Tree
    • Minimum Depth of Binary Tree
    • Balanced Binary Tree
    • Lowest Common Ancestor
    • Binary Tree Maximum Path Sum
    • Binary Tree Maximum Path Sum II
    • Binary Tree Level Order Traversal*
    • Binary Tree Level Order Traversal II
    • Binary Tree Zigzag Level Order Traversal
    • Validate Binary Search Tree
    • Inorder Successor in Binary Search Tree
    • Binary Search Tree Iterator
    • Search Range in Binary Search Tree
    • Insert Node in a Binary Search Tree
    • Remove Node in Binary Search Tree
    • Find the kth largest element in the BST
    • Kth Smallest Element in a BST
    • Serialize and Deserialize Binary Tree*
    • Construct Binary Tree from Preorder and Inorder Traversal
    • Convert Sorted Array to Binary Search Tree
    • Unique Binary Search Trees *
    • Unique Binary Search Trees II *
    • Recover Binary Search Tree
    • Same Tree
    • Symmetric Tree
    • Path Sum*
    • Path Sum II*
    • Flatten Binary Tree to Linked List
    • Populating Next Right Pointers in Each Node
    • Sum Root to Leaf Numbers
    • Binary Tree Right Side View
    • Count Complete Tree Nodes
    • Invert Binary Tree
    • Binary Tree Paths*
    • Subtree of Another Tree
  • A家面试总结
  • Expedia面经收集
  • Python 常用语句
  • lotusflare
  • Microsoft
  • 模板
  • Bing 组面试总结
  • 面试笔记
  • Sliding window
Powered by GitBook
On this page
  • Question
  • Example
  • Solution1
  • Solution 2
  • Solution 3
  • Solution 4

Was this helpful?

  1. Palindrome

Longest Palindromic Substring

Question

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Example

Given the string = "abcdzdcab", return "cdzdc".

Solution1

首先可以想到的方法是暴力解法,枚举所有子串,对每个子串判断是否为回文,复杂度为O\(n^3\),所以不推荐,比较容易想的解法是以当前的点为左右指针的两个点,然后左右移动,然后去比较当前最长的回文,如果大于就覆盖当前的最大回文的变量, 需要注意的就是有奇偶的情况。时间复杂度是:O(N)

class Solution:
    # @param {string} s input string
    # @return {string} the longest palindromic substring
    def longestPalindrome(self, s):
        if s == None or len(s) == 1:
            return s
        # Write your code here
        result = ''
        for i in range(len(s)):
            left, right = i, i + 1
            while left >= 0 and right < len(s) and s[left] == s[right]:
                if right - left + 1 > len(result):
                    result = s[left: right + 1]
                left -= 1
                right += 1

            left, right = i - 1, i + 1
            while left >= 0 and right < len(s) and s[left] == s[right]:
                if right - left + 1 > len(result):
                    result = s[left: right + 1]
                left -= 1
                right += 1

        return result

Solution 2

DP 方法,区间型动态规划的典型应用,在里面可以使用滑动变量,来不断更新最长字符串。比较tricky的地方是i + 1 > j -1的情况,有两种做法,可以一开始就初始化,从i 到j 只有一个或者两个元素的情况,或者把i + 1 > j - 1带入表达式,这样第二层的循环j 从 等于i 开始,否则如果前面初始化了,则可以直接从j = i + 2 -> n 开始循环。

class Solution:
    # @param {string} s input string
    # @return {string} the longest palindromic substring
    def longestPalindrome(self, s):
        # Write your code here
        n = len(s)
        longest = ''
        isPalin =  [[False for y in range(n)] for x in range(n)]
        # i + 1 > j -1 说明从i到j只有一个或者两个元素的时候,不需要进行isPalin[i][j] 判断。
        # 如果不进行i + 1> j- 1的判定,也可以初始化,i到j的一个到两个元素。

        for i in range(n - 1, -1, -1):
            for j in range(i, n):
                if (i + 1 > j - 1 or isPalin[i + 1][j - 1]) and s[i] == s[j]:
                    isPalin[i][j] = True
                    if len(s[i: j + 1]) > len(longest):
                        longest = s[i: j + 1]
        return longest

Solution 3

后缀法:

Solution 4

Manacher(马拉车) 算法, 这个不好想,也不好背诵,果断放弃。

PreviousPalindrome Partitioning IINextValid Palindrome

Last updated 4 years ago

Was this helpful?