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
  • 相关阅读:
    前端工程师必备:前端的模块化
    1414. 和为 K 的最少斐波那契数字数目(贪心)
    62. 不同路径(经典dp问题简单路径)
    1051. 高度检查器(排序比较)
    1144. 递减元素使数组呈锯齿状(两次扫)
    面试题 16.04. 井字游戏(模拟即可)
    微信小程序 base64ToArrayBuffer
    人人商城手机端添加控制器
    微擎自定义回复规则
    JS 对浏览器相关的操作
  • 原文地址:https://www.cnblogs.com/yancea/p/7911889.html
Copyright © 2011-2022 走看看