zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):030-Substring with Concatenation of All Words

    题目来源:

      https://leetcode.com/problems/substring-with-concatenation-of-all-words/


    题意分析:

      输入一个字符串s和一连串的长度相同的字符串数组words,找出仅由所有的words组成的s的子字符串起始位置。


    题目思路:

      由于给定的words的长度是相同的,题目难度就降低了很多。题目难度就在于判断一个字符串是否仅由words构成。这里,我们可以构造一个字典,key对应的是words出现的次数。将字符串截成n个words长度的字符串,如果这些字符串出现在字典里面,字典对应的次数-1.如果所有字典为0则满足。


    代码(python):

     1 class Solution(object):
     2     def match(self,s,dict,size):
     3         i = 0
     4         while i <= len(s)- size:
     5             tmp = s[i:i + size]
     6             if tmp in dict and dict[tmp] != 0:
     7                 dict[tmp] -= 1
     8             else:
     9                 return False
    10             i += size
    11         return True
    12     def findSubstring(self, s, words):
    13         """
    14         :type s: str
    15         :type words: List[str]
    16         :rtype: List[int]
    17         """
    18         sizew = len(words)
    19         if sizew == 0:
    20             return []
    21         d = {}
    22         ans = []
    23         for i in words:
    24             if i in d:
    25                 d[i] += 1
    26             else:
    27                 d[i] = 1
    28         j = 0
    29         ss = len(s); sw = len(words[0])
    30         while j <= ss - sizew * sw:
    31             tmpd = d.copy()
    32             if self.match(s[j:j + sizew * sw],tmpd,sw):
    33                 ans.append(j)
    34             j += 1
    35         return ans
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/4898993.html

  • 相关阅读:
    归并排序法实现
    HuffmanTree
    快速排序法的实现
    随机数发生器说明
    装箱问题改进
    瞬间判断2的幂
    weblogic删除域
    【转】Mock方法介绍
    Oracle 11G空表无法导出处理
    深入理解JVM虚拟机(一):JVM运行时数据区
  • 原文地址:https://www.cnblogs.com/chruny/p/4898993.html
Copyright © 2011-2022 走看看