Substring with Concatenation of All WordsFeb 24 '125071 / 18608
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
注:未通过所有case
“aaa”, [a, b],这个case我自己返回是空,但是在leetcode上返回(0,1)。让我很郁闷。
假如unordered_map可以算作是O(1)的话,则这个算法应该是O(n),n = S.size();
class Solution { public: unordered_map<string, int> dic; vector<int> t; void load(const string& s, const vector<string> &l) { int n = l.size(); int cnt = 0; for (int i = 0; i < n; ++i) { auto it = dic.find(l[i]); if (it == dic.end()) { dic[l[i]] = cnt++; t.push_back(1); } else { t[it->second]++; } } } vector<int> findSubstring(string S, vector<string> &L) { vector<int> res; int n = L.size(); int len = S.size(); int K = L[0].size(); load(S, L); vector<int> v(len); for (int i = 0; i < len - K; ++i) { auto it = dic.find(S.substr(i, K)); if (it == dic.end()) v[i] = -1; else v[i] = it->second; } int total = 0, last = len - K * n; vector<bool> mk(len, false); res.clear(); for (int i = 0; i <= last; ++i) { if (mk[i]) continue; int start = i, end, cur; while (start <= last && dic.find(S.substr(start, K)) == dic.end()) mk[start] = true,start += K; if (start > last) continue; if (n == 1) { res.push_back(start); mk[start] = true; continue; } end = start + K; vector<int> cnt(t); total = 1; auto it = dic.find(S.substr(start, K)); cnt[it->second]--; while (end < len) { auto ie = dic.find(S.substr(end, K)); if (ie == dic.end()) { while (start <= end) mk[start] = true, start += K; break; } else { cur = ie->second; if (cnt[cur] == 0) { while (start <= end) { mk[start] = true; cnt[v[start]]++; total--; if (cur == v[start]) break; start += K; } } cnt[cur]--; total ++; if (total == n) { res.push_back(start); cnt[v[start]]++; total--; mk[start]=true; start += K; } end += K; } } } return res; } };
相关推荐
本文详细解析了LeetCode上编号为30的算法题目“Substring with Concatenation of All Words”,以及如何使用JavaScript来实现其解决方案。题目要求编写一个函数,接受两个字符串s和words作为参数,s是主字符串,...
c c语言_leetcode 0030_substring_with_concatenation_of_all_words.zip
leetcode 跳跃 LeetCode Exercises from leetcode. All the exercises is uesd by microsoft to interview. The following is the number of the questions form Leetcode. 4 寻找两个正序数组的中位数 median of ...
Concatenation of All Words 哈希表 注意匹配方向 Valid Sudoku 数组 遍历 Sudoku Solver 深度优先遍历 回溯 先检查后修改 Group Anagrams 排序 unordered_map Minimum Window Substring 两个指针遍历 map Maximal ...
Here is the classification of all `468` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and...