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

  • 相关阅读:
    有关敏捷(1)
    有关创业的想法
    2010必须做到的事
    技术搜索还是谷歌强
    错误处理的一些想法
    定期自动删除数据
    ip
    asp.ent Repeter实现分页
    QQ客服在线聊天
    几种文件上传的方法
  • 原文地址:https://www.cnblogs.com/chruny/p/4898993.html
Copyright © 2011-2022 走看看