LeetCode #30 Substring with Concatenation of All Words 串聯(lián)所有單詞的子串

30 Substring with Concatenation of All Words 串聯(lián)所有單詞的子串

Description:
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example:

Example 1:

Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.

Example 2:

Input:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
Output: []

題目描述:
給定一個字符串 s 和一些長度相同的單詞 words课兄。找出 s 中恰好可以由 words 中所有單詞串聯(lián)形成的子串的起始位置恕沫。

注意子串要與 words 中的單詞完全匹配,中間不能有其他字符量愧,但不需要考慮 words 中單詞串聯(lián)的順序佑附。

示例 :

示例 1:

輸入:
s = "barfoothefoobarman",
words = ["foo","bar"]
輸出:[0,9]
解釋:
從索引 0 和 9 開始的子串分別是 "barfoo" 和 "foobar" 。
輸出的順序不重要, [9,0] 也是有效答案。

示例 2:

輸入:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
輸出:[]

思路:

  1. 對 words進(jìn)行排序, 遍歷字符串 s, 找出 words中的長度的字符串并排序再與排序后的 words的拼接結(jié)果比較, 相同就加入結(jié)果中
    時間復(fù)雜度O(nmlgm), 空間復(fù)雜度O(m), 其中 n表示 s的長度, m表示 words拼接之后的長度
  2. 對于 方法1, 可以用哈希表存放 words并比較, 可以減少排序帶來的時間
    時間復(fù)雜度O(nm), 空間復(fù)雜度O(m)
  3. 滑動窗口
    時間復(fù)雜度O(n), 空間復(fù)雜度O(m)

代碼:
C++:

class Solution 
{
public:
    vector<int> findSubstring(string s, vector<string>& words) 
    {
        vector<int> result;
        if (s.size() == 0 or words.size() == 0) return result;
        unordered_map<string, int> m;
        int word_size = words[0].size(), words_size = words.size(), s_size = s.size();
        for (auto word : words) ++m[word];
        for (int i = 0; i < word_size; i++) 
        {
            int left = i, right = i, count = 0;
            unordered_map<string, int> temp;
            while (right + word_size <= s_size) 
            {
                string word = s.substr(right, word_size);
                right += word_size;
                if (m.find(word) == m.end()) 
                {
                    count = 0;
                    left = right;
                    temp.clear();
                } 
                else 
                {
                    ++temp[word];
                    ++count;
                    while (temp[word] > m[word]) 
                    {
                        string test = s.substr(left, word_size);
                        --count;
                        --temp[test];
                        left += word_size;
                    }
                    if (count == words_size) result.push_back(left);
                }
            }
        }
        return result;
    }
};

Java:

class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> result = new ArrayList<>();
        if (s.length() == 0 || words.length == 0) return result;
        HashMap<String, Integer> map = new HashMap<>();
        int word_size = words[0].length(), words_size = words.length, s_size = s.length();
        for (String word : words) map.put(word, map.getOrDefault(word, 0) + 1);
        for (int i = 0; i < word_size; i++) {
            int left = i, right = i, count = 0;
            HashMap<String, Integer> temp = new HashMap<>();
            while (right + word_size <= s_size) {
                String word = s.substring(right, right + word_size);
                right += word_size;
                if (!map.containsKey(word)) {
                    count = 0;
                    left = right;
                    temp.clear();
                } else {
                    temp.put(word, temp.getOrDefault(word, 0) + 1);
                    count++;
                    while (temp.getOrDefault(word, 0) > map.getOrDefault(word, 0)) {
                        String test = s.substring(left, left + word_size);
                        count--;
                        temp.put(test, temp.getOrDefault(test, 0) - 1);
                        left += word_size;
                    }
                    if (count == words_size) result.add(left);
                }
            }
        }
        return result;
    }
}

Python:

class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        if not words or len(s) < len(words[0]) * len(words):
            return []
        result, wide, num, n, total = list(), len(words[0]), len(words), len(s), len(words[0]) * len(words)
        words.sort()
        for i in range(n + 1 - total):
            l = [s[j : j + wide] for j in range(i, i + total, wide)]
            l.sort()
            if l == words:
                result.append(i)
        return result
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末鼓鲁,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子仔沿,更是在濱河造成了極大的恐慌坐桩,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件封锉,死亡現(xiàn)場離奇詭異绵跷,居然都是意外死亡膘螟,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進(jìn)店門碾局,熙熙樓的掌柜王于貴愁眉苦臉地迎上來荆残,“玉大人,你說我怎么就攤上這事净当∧谒梗” “怎么了?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵像啼,是天一觀的道長俘闯。 經(jīng)常有香客問我,道長忽冻,這世上最難降的妖魔是什么真朗? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮僧诚,結(jié)果婚禮上遮婶,老公的妹妹穿的比我還像新娘。我一直安慰自己湖笨,他們只是感情好旗扑,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著慈省,像睡著了一般臀防。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上辫呻,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天清钥,我揣著相機(jī)與錄音,去河邊找鬼放闺。 笑死祟昭,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的怖侦。 我是一名探鬼主播篡悟,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼匾寝!你這毒婦竟也來了搬葬?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤艳悔,失蹤者是張志新(化名)和其女友劉穎急凰,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體猜年,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡抡锈,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年疾忍,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片床三。...
    茶點(diǎn)故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡一罩,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出撇簿,到底是詐尸還是另有隱情聂渊,我是刑警寧澤,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布四瘫,位于F島的核電站汉嗽,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏莲组。R本人自食惡果不足惜诊胞,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一暖夭、第九天 我趴在偏房一處隱蔽的房頂上張望锹杈。 院中可真熱鬧,春花似錦迈着、人聲如沸竭望。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽咬清。三九已至,卻和暖如春奴潘,著一層夾襖步出監(jiān)牢的瞬間旧烧,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工画髓, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留掘剪,地道東北人。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓奈虾,卻偏偏與公主長得像夺谁,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子肉微,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評論 2 355

推薦閱讀更多精彩內(nèi)容