1. 程式人生 > >LeetCode:30. Substring with Concatenation of All Words

LeetCode:30. Substring with Concatenation of All Words

問題描述:

30. 與所有單詞相關聯的字串

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

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

示例 1:

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

示例 2:

輸入: s = “wordgoodstudentgoodword”, words = [“word”,“student”] 輸出: []

問題分析:

這個題目看著很複雜,其實不難,可以用滑動視窗的方法解決,先把 words中的所有單詞進行放到一個字典中,然後掃描字串s,一個視窗一個視窗的統計分析,把符合的小視窗的起始位置儲存結果變數裡,即可。

Python3實現:

# @Time   :2018/09/24
# @Author :LiuYinxing


class Solution:
    def findSubstring(self, s, words):

        if len(words) == 0: return []
        wordsDict = {}
        for word in words:
# 統計每個單詞出現的個數 if word not in wordsDict: wordsDict[word] = 1 else: wordsDict[word] += 1 n, m, k = len(s), len(words[0]), len(words) # n, m, k 分別表示,字串的長度,單詞的長度,單詞的個數 res = [] for i in range(n - m * k + 1): # 選擇一個區間或者視窗
j = 0 cur_dict = {} while j < k: word = s[i + m * j:i + m * j + m] # 區間內選擇一個單詞 if word not in wordsDict: # 出現不存在的單詞,直接結束本此區間 break if word not in cur_dict: cur_dict[word] = 1 else: cur_dict[word] += 1 if cur_dict[word] > wordsDict[word]: # 某個單詞大於所需,則直接結束本此區間 break j += 1 # 單詞數加一 print(j) if j == k: res.append(i) # 記錄起始位置 return res if __name__ == '__main__': solu = Solution() s, words = 'barfoothefoobarman', ['foo', 'bar'] print(solu.findSubstring(s, words))

宣告: 總結學習,有問題可以批評指正,大神可以略過哦