Leetcode-30-Substring with Concatenation of All Words
題目
You are given a string s and an array of strings words. All the strings of words are of the same length.
A concatenated string is a string that exactly contains all the strings of any permutation of words concatenated.
- For example, if words = [“ab”,”cd”,”ef”], then “abcdef”, “abefcd”, “cdabef”, “cdefab”, “efabcd”, and “efcdab” are all concatenated strings. “acdbef” is not a concatenated string because it is not the concatenation of any permutation of words.
Return an array of the starting indices of all the concatenated substrings in s. You can return the answer in any order.
Example 1
1 | Input: s = "barfoothefoobarman", words = ["foo","bar"] |
Example 2
1 | Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"] |
Example 3
1 | Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"] |
解釋題目
題目會給一個 string array words,words 內的每個字串的長度都相同。
permutation words 的定義是words 內的每個字串任意排列,但字元之間不能任意排列
。
- Ex: words = [“foo”,”bar”]
- permutation words = foobar, barfoo
not
permutation words = bafoor
題目還會給一個 string s,在 s 內找到所有 permutation words 的 起始位置
。
思路
- i 是左指針,記錄當前尋找的 permutation words 的
起始位置
。 - j 是右指針,尋找可能的答案。
- Table 記錄 words 中,每個 string 出現的次數。
- COUNT 記錄 words 中總共有幾個 string。
圖解
外層迴圈,設成 words[0].size() 的原因 :
程式主要邏輯 :
程式碼
1 | class Solution { |
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 記錄程式的地方!
評論