[LeetCode]Palindromic Substrings

题目描述:

LeetCode 647. Palindromic Substrings

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".

Note:

  1. The input string length won't exceed 1000.

题目大意:

给定字符串,计算其中的回文子串的个数。

解题思路:

队列(Queue)

初始化空队列queue

将字符串中的所有字符,以及长度为2并且形如'aa'的子串的起止下标数对(left, right)加入queue

循环直到队列为空:

  将队首弹出,记为(left, right),将计数器+1

  若(left - 1, right + 1)索引范围有效,并且s[left - 1] == s[right + 1],将其加入queue

Python代码:

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        size = len(s)
        queue = collections.deque((x, x) for x in range(size))
        for x in range(size - 1):
            if s[x] == s[x + 1]:
                queue.append((x, x + 1))
        ans = 0
        while queue:
            x, y = queue.popleft()
            ans += 1
            if x - 1 >= 0 and y + 1 < size and s[x - 1] == s[y + 1]:
                queue.append((x - 1, y + 1))
        return ans

本文链接:http://bookshadow.com/weblog/2017/07/24/leetcode-palindromic-substrings/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

评论
  1. 书影网友 书影网友 发布于 2017年7月30日 02:27 #

    认真进行了学习。

张贴您的评论