LeetCode Substring with Concatenation of All Words
来源:互联网 发布:云计算数据中心 用电 编辑:程序博客网 时间:2024/06/10 20:30
问题网址:https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/
问题描述:
给你一个字符串s和一个长度相同的单词列表。 找出s中所有子字符串的起始索引,这些字符串中的每个单词只是一个字符串,没有任何中介字符。
例如,给出:
s:“barfoothefoobarman”
词语:[“foo”,“bar”]
你应该返回索引:[0,9]。
(顺序无关紧要)。
一个O(N)的解法
// travel all the words combinations to maintain a window // there are wl(word len) times travel // each time, n/wl words, mostly 2 times travel for each word // one left side of the window, the other right side of the window // so, time complexity O(wl * 2 * N/wl) = O(2N) vector<int> findSubstring(string S, vector<string> &L) { vector<int> ans; int n = S.size(), cnt = L.size(); if (n <= 0 || cnt <= 0) return ans; // init word occurence unordered_map<string, int> dict; for (int i = 0; i < cnt; ++i) dict[L[i]]++; // travel all sub string combinations int wl = L[0].size(); for (int i = 0; i < wl; ++i) { int left = i, count = 0; unordered_map<string, int> tdict; for (int j = i; j <= n - wl; j += wl) { string str = S.substr(j, wl); // a valid word, accumulate results if (dict.count(str)) { tdict[str]++; if (tdict[str] <= dict[str]) count++; else { // a more word, advance the window left side possiablly while (tdict[str] > dict[str]) { string str1 = S.substr(left, wl); tdict[str1]--; if (tdict[str1] < dict[str1]) count--; left += wl; } } // come to a result if (count == cnt) { ans.push_back(left); // advance one word tdict[S.substr(left, wl)]--; count--; left += wl; } } // not a valid word, reset all vars else { tdict.clear(); count = 0; left = j + wl; } } } return ans; }
阅读全文