LeetCode Substring with Concatenation of All Words
2017-12-25 22:49
381 查看
问题网址:https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/
问题描述:
给你一个字符串s和一个长度相同的单词列表。 找出s中所有子字符串的起始索引,这些字符串中的每个单词只是一个字符串,没有任何中介字符。
例如,给出:
s:“barfoothefoobarman”
词语:[“foo”,“bar”]
你应该返回索引:[0,9]。
(顺序无关紧要)。
一个O(N)的解法
4000
问题描述:
给你一个字符串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; }
4000
相关文章推荐
- leetcode:Substring with Concatenation of All Words
- LeetCode-Substring with Concatenation of All Words
- [leetcode]Substring with Concatenation of All Words @ Python
- LeetCode Online Judge 题目C# 练习 - Substring with Concatenation of All Words
- leetcode:Substring with Concatenation of All Words
- leetcode 之 Substring with Concatenation of All Words
- leetcode:Substring with Concatenation of All Words
- leetcode 30. Substring with Concatenation of All Words
- leetcode第一刷_Substring with Concatenation of All Words
- [Leetcode] 30. Substring with Concatenation of All Words 解题报告
- leetcode: Substring with Concatenation of All Words
- [leetcode]Substring with Concatenation of All Words
- LeetCode 30. Substring with Concatenation of All Words
- [LeetCode][Java] Substring with Concatenation of All Words
- 【leetcode】第30题 Substring with Concatenation of All Words
- leetcode-30. Substring with Concatenation of All Words
- [LeetCode] 30. Substring with Concatenation of All Words 解题思路 - Java
- LeetCode(30) Substring with Concatenation of All Words (java)
- leetcode - Substring with Concatenation of All Words
- [leetcode] Substring with Concatenation of All Words