題目.
很有意思
首先想到的就是動態規劃,當多乙個字串的字元的時候,要麼增加的這個字元起到了作用,要麼沒起到作用。更進一步,我們不需要之前的狀態,所以動態規劃的陣列也省了。
func
checkmatch
(subs string
, wordsmap map
[string
]int
, wordlen int
)bool
iflen
(checkwords)
!=len
(wordsmap)
for k, v :=
range wordsmap
}return
true
}func
findsubstring
(s string
, words [
]string)[
]int
wordlen :=
len(words[0]
) sublen :=
len(words)
* wordlen
iflen
(s)< sublen
wordmap :=
make
(map
[string
]int
)for
_, v :=
range words
for i :=
0; i <=
len(s)
-sublen; i++
}return result
}
o(nmk)
o(1)
執行用時 :104 ms, 在所有 golang 提交中擊敗了39.05%的使用者
記憶體消耗 :7.4 mb, 在所有 golang 提交中擊敗了8.11%的使用者
這個演算法並不理想,原因在於checkmatch函式複雜度太高,可以利用滑動視窗優化checkmatch,並且充分利用等長這個條件,把等長字元當做乙個字串處理。
package main
import
("fmt"
)func
checkequal
(tmp, wordmap map
[string
]int
)bool
}return
true
}func
findsubstring
(s string
, words [
]string)[
]int
wordlen :=
len(words[0]
) sublen :=
len(words)
* wordlen
iflen
(s)< sublen
wordmap :=
make
(map
[string
]int
)for
_, v :=
range words
for start :=
0; start < wordlen; start++
tmp[s[first:first+wordlen]]--
first += wordlen
}}}return result
}func
main()
fmt.
println
(findsubstring
(s, words)
)}
執行用時 :16 ms, 在所有 golang 提交中擊敗了72.78%的使用者
記憶體消耗 :6.3 mb, 在所有 golang 提交中擊敗了62.16%的使用者
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中單詞串聯的順序。輸入 s barfoothefoobarman words foo bar 輸出 0,...
30 串聯所有單詞的子串
給定乙個字串s和一些長度相同的單詞words。找出s中恰好可以由words中所有單詞串聯形成的子串的起始位置。注意子串要與words中的單詞完全匹配,中間不能有其他字元,但不需要考慮words中單詞串聯的順序。示例 1 輸入 s barfoothefoobarman words foo bar 輸出...