zoukankan      html  css  js  c++  java
  • 647. Palindromic Substrings(Medium)

    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.

    题意:给定字符串,计算其中的回文子串的个数;其中,每个子串拥有不同的start indexes 和 end indexes;

    思路:利用队列(Queue)思想

       1.初始化空队列queue;

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

       3.循环直到队列为空:将队首弹出,记为(left, right),计数结果加1;

                 如果(left - 1, right + 1)是有效范围,且s[left - 1] == s[right + 1],就将其加入queue。

    import collections
    
    
    class Solution1:
        def countSubstrings(self, s):
    
            queue = collections.deque((x, x) for x in range(len(s)))
            for x in range(len(s) - 1):
                if s[x] == s[x + 1]:
                    queue.append((x, x + 1))
    
            res= 0
            while queue:
                x, y = queue.popleft()
                res += 1
                if x - 1 >= 0 and y + 1 < len(s) and s[x - 1] == s[y + 1]:
                    queue.append((x - 1, y + 1))
            return res

        第二种解法如下:

    class Solution2:
        def countSubstrings(self, s):
            """
            :type s: str
            :rtype: int
            """
            num = 0
            for i in range(0, len(s)+1):
                for j in range(i+1, len(s)+1):
                    sub = s[i:j]
                    if(sub == sub[::-1]):
                        num +=1
            return num
  • 相关阅读:
    HDU 1002 A + B Problem II
    leetcode 42.接雨水
    无向图 及其术语
    C++优先队列详解
    C++优先队列详解
    最短路
    最短路
    CF DP练习题
    CF DP练习题
    干货
  • 原文地址:https://www.cnblogs.com/yancea/p/7911889.html
Copyright © 2011-2022 走看看