[HashTable]030 Substring with Concatenation of All Words

  • 分類:HashTable

  • 考察知識點:HashTable 數(shù)組遍歷

  • 最優(yōu)解時間復(fù)雜度: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中去,然后在每次循環(huán)的時候弄一個dict_copy,再循環(huán)判斷dict_copy中的數(shù)據(jù)

貌似是我有史以來速度最慢的一次
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,260評論 0 23
  • 初夏的早上,急匆匆的倒了一班車,看看時間,還早。默默的看著車窗外發(fā)呆。曾經(jīng)母親感嘆說,這日子真不見混??!我卻想,未...
    s七貓閱讀 253評論 0 2
  • 今天參加了院里召開的座談會,邀請的是加拿大的一個教授,會上交流了雙方教學(xué)和科研多個方面的內(nèi)容。 印象最深的有這么幾...
    慧妍日記閱讀 391評論 3 2
  • 【生活的含義】一個浪打上礁石,海鳥驚逃,以為是一次謀殺。一個浪撲上海灘,孩子歡喜,以為是大海開出了鮮花。同樣的事物...
    杭杭出狀元閱讀 274評論 0 9

友情鏈接更多精彩內(nèi)容