[LeetCode] Substring with Concatenation of All Words

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Substring with Concatenation of All Words相关的知识,希望对你有一定的参考价值。

主要思路是:

1. 将words中的每个单词看作一个单元,每个单元长度是c,则s可以切成c个list,每个list是由c个字符组成的单元组。

2. 维护长度为words.size()的滑块,计算每个滑块内是否正好由words中所有单词组成。

3. 将移动滑块的操作优化到O(1) 或 O(logN)

   滑块内的内容要不填满words,超出的部分和不是words中的部分放入others中。

 

 1 class Solution {
 2 public:
 3     vector<int> findSubstring(string s, vector<string>& words) {
 4         vector<int> ans;
 5         if (s.size() == 0 || words.size() == 0 || words[0].size() == 0) return ans;
 6         int wl = words[0].size();
 7         int n = s.size();
 8         int m = words.size();
 9         map<string, int> ms;
10         for (const auto& c : words) {
11             if (ms.find(c) != ms.end()) {
12                 ms[c] += 1;
13             } else {
14                 ms[c] = 1;
15             }
16         };
17         
18         for (int i = 0; i < wl && i < n; i++) {
19             int count = m;
20             map<string, int> ws = ms;
21             multiset<string> others;
22             for (int j = i; j < n; j += wl) {
23                 int r = j - m*wl;
24                 //recover
25                 if (r >= 0) {
26                     string tmp = s.substr(r, wl);
27                     if (others.count(tmp)) {
28                         others.erase(others.find(tmp));
29                     } else {
30                         ws[tmp] ++;
31                         count ++;
32                     }
33                 }
34                 //do
35                 string tmp = s.substr(j, wl);
36                 if (ws.count(tmp) && ws[tmp] > 0) {
37                     count --;
38                     ws[tmp] --;
39                 } else {
40                     others.insert(tmp);
41                 }
42                 if (count == 0 && others.size() == 0) {
43                     ans.push_back(j - (m-1)*wl);
44                 }
45             }
46         }
47         sort(ans.begin(), ans.end());
48         return ans;
49     }
50 };

 

以上是关于[LeetCode] Substring with Concatenation of All Words的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 30 Substring with Concatenation of All Words

LeetCode - 30. Substring with Concatenation of All Words

LeetCode 395. Longest Substring with At Least K Repeating Characters

leetcode python 030 Substring with Concatenation of All Words

LeetCode(30) Substring with Concatenation of All Words

LeetCode30. Substring with Concatenation of All Words