leetcode 030. 與所有單詞相關(guān)聯(lián)的字串

給定一個字符串 s 和一些長度相同的單詞 words。s 中找出可以恰好串聯(lián) words 中所有單詞的子串的起始位置。

注意子串要與 words 中的單詞完全匹配,中間不能有其他字符,但不需要考慮 words 中單詞串聯(lián)的順序。

示例 1:

輸入:
s =
"barfoothefoobarman",
words = ["foo","bar"]
輸出: [0,9]
解釋: 從索引 0 和 9 開始的子串分別是 "barfoor" 和 "foobar" 。
輸出的順序不重要, [9,0] 也是有效答案。

class Solution:
    def findSubstring(self, s, words):
        dic_words = {}
        if not (s and words):
            return []
        for word in words:
            if word in dic_words:
                dic_words[word] += 1
            else:
                dic_words[word] = 1
        len_s = len(s)
        len_word = len(words[0])
        count_words = len(words)
        res = []
        for i in range(len_s - count_words * len_word + 1):
            j = 0
            dic_tmp = {}
            while j < count_words:  # 把單詞數(shù)量都取完
                tmp_word = s[i + j * len_word: i + (j + 1) * len_word]
                if tmp_word not in dic_words: # 如果不在目標(biāo)字典就退出
                    break
                if tmp_word in dic_words and tmp_word not in dic_tmp:
                    dic_tmp[tmp_word] = 1
                else:
                    dic_tmp[tmp_word] += 1
                    if dic_tmp[tmp_word] > dic_words[tmp_word]: # 如果超過單詞數(shù)量就退出
                        break
                j += 1
            else: # 循環(huán)完成后表示所有單詞都統(tǒng)計完成
                res.append(i)
        return res


su = Solution()
s = "wordgoodgoodgoodbestword"
words = ["word", "good", "best", "word"]
res = su.findSubstring(s, words)
print(res)
?著作權(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)容

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