Leetcode做題日記:30. 與所有單詞相關聯的字串(PYTHON)
阿新 • • 發佈:2019-01-01
給定一個字串 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”]
輸出: []
第一次的程式碼,擊敗4.85%。。。
思路很簡單,words總共需要zL個字母,在s中擷取zL個字母,在這個片段中依次擷取Lonew個字母組成的單詞,判斷是否在words中,為了避免重複,在words中判斷過的單詞就刪除,如果最後words中全部刪除,就表示總共擷取的這堆字母是正確是,然後再開始下一輪迭代
if len(words)==0:
return []
Lonew=len(words[0]) #記錄一個單詞的長度
Lw=len(words)
zL=Lonew*Lw #需要字母的總長度
Ls= len(s)
i=0
I=[]
if Ls<zL or Ls==0:
return I
while i<=Ls-zL:
if s[i:i+Lonew] not in words: #加上這個可以加快程式
i=i+1 #不然會提前超時
continue #即如果第一個單詞就不在words裡,就跳過
S=s[i:i+zL]
w=words[:]
for j in range(0,zL,Lonew): #range(,,)不是range(::)
SS=S[j:j+Lonew]
if SS in w:
w.remove(SS) #一開始寫的是w.pop(SS),不行
else: #如果不新增這句,永遠超時
break
if w==[]:
I.append(i)
i=i+1
return I