給定乙個字串 s 和一些長度相同的單詞words
。找出s
中恰好可以由words
中所有單詞串聯形成的子串的起始位置。
注意子串要與words
中的單詞完全匹配,中間不能有其他字元,但不需要考慮words
中單詞串聯的順序。
輸入:
s = "barfoothefoobarman",
words = ["foo","bar"]
輸出:[0,9]
解釋:從索引 0 和 9 開始的子串分別是 "barfoor" 和 "foobar" 。
輸出的順序不重要, [9,0] 也是有效答案。
輸入:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
輸出:
class
solution
:def
findsubstring
(self, s:
str, words: list[
str])-
> list[
int]
: res =
ifnot words:
return res
words_count, word_len =
len(words)
,len
(words[0]
)# 單詞個數和每個單詞長度
words_dict, s_len =
,len
(s)for word in words:
words_dict[word]
= words_dict.get(word,0)
+1for i in
range
(word_len)
:# 根據單詞長度劃分幾塊
left, right, count, now_dict = i, i,0,
# 起始單詞位置, 單詞數, 單詞字典
while right <= s_len - word_len:
right_str = s[right:right+word_len]
if right_str not
in words_dict:
# 詞不在words中, 從right右邊重新開始
count, now_dict, right =0,
, right + word_len
left = right
else
: now_dict[right_str]
= now_dict.get(right_str,0)
+1right += word_len
count +=
1while now_dict[right_str]
> words_dict[right_str]
:# 謀個詞多了, 所以就要把多了的這個詞在前面的去掉乙個
left_str = s[left:left+word_len]
now_dict[left_str]-=1
count -=
1 left += word_len
if count == words_count:
#如果 dict 和 count都沒有問題, 說明匹配
# 之後的left後移一位
now_dict[s[left:left+word_len]]-=
1 count -=
1 left += word_len
return res
30 串聯所有單詞的子串
本文參考 一開始的思路是使用遞迴做出words所有結合情況的字典 然後在s中擷取words長度去查字典 結果超時了 超時 class solution for int i 0 i chang i return vectorfindsubstring string s,vector words vec...
30 串聯所有單詞的子串
給定乙個字串s和一些長度相同的單詞words。找出s中恰好可以由words中所有單詞串聯形成的子串的起始位置。注意子串要與words中的單詞完全匹配,中間不能有其他字元,但不需要考慮words中單詞串聯的順序。示例 1 輸入 s barfoothefoobarman words foo bar 輸出...
30 串聯所有單詞的子串
題目.很有意思 首先想到的就是動態規劃,當多乙個字串的字元的時候,要麼增加的這個字元起到了作用,要麼沒起到作用。更進一步,我們不需要之前的狀態,所以動態規劃的陣列也省了。func checkmatch subs string wordsmap map string int wordlen int b...