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
  • 相关阅读:
    zoj 2165
    zoj 1005 Jugs
    谈如何使用c中的qsort快速排序库函数 按主次关键字正确排序
    zoj 3197 Google Book
    zoj 3710 Friends
    IOS编程中比较两个日期的大小
    iOS中常用的四种数据持久化方法简介
    iphone开发基础:loadView/viewDidLoad/initWithNibName/awakeFromNib/initWithCoder的用法
    不通过AppStore发布iOS应用教程
    iOS之视频播放MPMoviePlayerViewController
  • 原文地址:https://www.cnblogs.com/yancea/p/7911889.html
Copyright © 2011-2022 走看看