1065. Index Pairs of a String
題目網址:https://leetcode.cn/problems/index-pairs-of-a-string/
題意:給一 string
text
和 string listwords
, 求所有index pair
使得text[i~j]
出現在words
中。
Solution 1:
想法:暴力搜尋法
class Solution { |
令總共有 n
個 word, 其中 $w_i$ 代表 words[i]
的長度, 且 text 之長度為 m
- time:$O(m^2 \cdot \displaystyle\sum_{i=1}^{n}w_i)$ ➔ 因為 c++ 的
find()
不是用 KMP 實作的- $O(m^2)$:每次以
start
為起點往後遍歷, 取text[start:end]
然後去判斷是否在wordset
中- $m + (m-1) + (m-2) + … + 1$ = $\dfrac{(m+1)\cdot m}{2}$
- $O(\displaystyle\sum_{i=1}^{n}w_i)$:每次判斷
text[start:end]
是否在wordset
中
- $O(m^2)$:每次以
- space:$O(\displaystyle\sum_{i=1}^{n}w_i)$ ➔
wordset
Solution 2:
想法:利用 Trie(prefix tree), 可參考 208. Implement Trie (Prefix Tree)
class TrieNode { |
令總共有 n
個 word, 其中 $w_i$ 代表 words[i]
的長度, 且 text 之長度為 m
- time:$O(\displaystyle\sum_{i=1}^{n}w_i + m^2)$
- $O(\displaystyle\sum_{i=1}^{n}w_i)$ : insert 所有 word 到 Trie 中
- $O(m^2)$ : 每次以
start
為起點往後遍歷, 判斷text[start:end]
是否在 Trie 中- $m + (m-1) + (m-2) + … + 1 =$ $\dfrac{(m+1)\cdot m}{2}$
- space:$O(26 \cdot \displaystyle\sum_{i=1}^{n}w_i)$ ➔ worse case : 每個 word 的
prefix
皆不重覆- 總共
n
個 word, 每一個 word 有 $w_i$ 個 node, 而每個 node 又有 26 個 children
- 總共
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論