Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Palindromic Substrings

$
0
0

题目描述:

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: 3Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input:"aaa"Output: 6Explanation: 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

Viewing all articles
Browse latest Browse all 559

Latest Images

Trending Articles



Latest Images