[HashTable]030 Substring with Concatenation of All Words

  • 分类:HashTable

  • 考察知识点:HashTable 数组遍历

  • 最优解时间复杂度:O(nm+n)*

30. Substring with Concatenation of All Words

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Input:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.

Example 2:

Input:
  s = "wordgoodstudentgoodword",
  words = ["word","student"]
Output: []

代码:

解法:

class Solution:
    def findSubstring(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: List[int]
        """
        #先判定边界条件
        if len(s)==0 or len(words)==0:
            return []
        
        #先把这个words存到
        words_length=len(words)
        word_length=len(words[0])
        
        if len(s)<word_length*words_length:
            return []
        
        words_dict={}
        for word in words:
            if word not in words_dict:
                words_dict[word]=1
            else:
                words_dict[word]+=1
        
        res=[]
        for i in range(len(s)-words_length*word_length+1):
            words_dict_copy=words_dict.copy()
            start=i
            count=words_length
            while(count>0):
                if s[start:start+word_length] not in words_dict_copy:
                    i
                    break
                if words_dict_copy[s[start:start+word_length]]==0:
                    break
                words_dict_copy[s[start:start+word_length]]-=1
                start+=word_length
                count-=1
            if count==0:
                res.append(i)
        return res

讨论:

1.这道题目是道Hard题,我就不深究它了,Beats的人少就少吧
2.这道题的思路是首先判断是否可以返回空的几个条件,然后再是把words全部放到dict中去,然后在每次循环的时候弄一个dict_copy,再循环判断dict_copy中的数据

貌似是我有史以来速度最慢的一次
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,178评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,501评论 0 23
  • 初夏的早上,急匆匆的倒了一班车,看看时间,还早。默默的看着车窗外发呆。曾经母亲感叹说,这日子真不见混啊!我却想,未...
    s七猫阅读 1,630评论 0 2
  • 今天参加了院里召开的座谈会,邀请的是加拿大的一个教授,会上交流了双方教学和科研多个方面的内容。 印象最深的有这么几...
    慧妍日记阅读 2,750评论 3 2
  • 【生活的含义】一个浪打上礁石,海鸟惊逃,以为是一次谋杀。一个浪扑上海滩,孩子欢喜,以为是大海开出了鲜花。同样的事物...
    杭杭出状元阅读 1,571评论 0 9

友情链接更多精彩内容