Leetcode刷题笔记,palindromic strings回文

647. Palindromic Substrings 求回文,感觉有点难不知道为什么放在DP,不是用DP解

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
       
        n = len(s)
        res = 0
        for i in xrange(len(s)):
            # add itself
            res += 1
            
            # even
            left = i
            right = i + 1
            while left >= 0 and right <= n-1 and s[left] == s[right]:
                res += 1
                left -= 1
                right += 1
                
            # odd
            left = i-1
            right = i+1
            while left >= 0 and right <= n-1 and s[left] == s[right]:
                res += 1
                left -= 1
                right += 1
        
        return res

 5. Longest Palindromic Substring

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

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s) < 2:
            return s

        self.n = len(s)
        self.left = len(s) - 1
        self.long = 0

        for i in xrange(self.n):
            print i
            self.helper(i, i + 1, s)  # even length
            self.helper(i - 1, i + 1, s)  # old length

        return s[self.left:self.left + self.long]

    def helper(self, left, right, s):
        while left >= 0 and right < self.n and s[left] == s[right]:
            left -= 1
            right += 1
        left += 1
        right -= 1
        if right - left + 1 > self.long:
            self.long = right - left +1
            self.left = left

猜你喜欢

转载自blog.csdn.net/Sengo_GWU/article/details/81814373