This commit is contained in:
Sainnhe Park 2022-11-16 10:58:20 +08:00
parent 9f4193858f
commit 8901afccf4
3 changed files with 67 additions and 0 deletions

View File

@ -0,0 +1,15 @@
#ifndef S0030_SUBSTRING_WITH_CONCATENATION_OF_ALL_WORDS
#define S0030_SUBSTRING_WITH_CONCATENATION_OF_ALL_WORDS
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words);
};
#endif

View File

@ -0,0 +1,33 @@
#include "s0030_substring_with_concatenation_of_all_words.hpp"
vector<int> Solution::findSubstring(string s, vector<string>& words) {
vector<int> res;
int m = words.size(), n = words[0].size(), ls = s.size();
for (int i = 0; i < n && i + m * n <= ls; ++i) {
unordered_map<string, int> differ;
for (int j = 0; j < m; ++j) {
++differ[s.substr(i + j * n, n)];
}
for (string& word : words) {
if (--differ[word] == 0) {
differ.erase(word);
}
}
for (int start = i; start < ls - m * n + 1; start += n) {
if (start != i) {
string word = s.substr(start + (m - 1) * n, n);
if (++differ[word] == 0) {
differ.erase(word);
}
word = s.substr(start - n, n);
if (--differ[word] == 0) {
differ.erase(word);
}
}
if (differ.empty()) {
res.emplace_back(start);
}
}
}
return res;
}

View File

@ -0,0 +1,19 @@
#include "s0030_substring_with_concatenation_of_all_words.hpp"
#include <gtest/gtest.h>
TEST(Problem30, Case1) {
string s{"barfoothefoobarman"};
vector<string> words{"foo", "bar"};
vector<int> o{0, 9};
Solution solution;
EXPECT_EQ(solution.findSubstring(s, words), o);
}
TEST(Problem30, Case2) {
string s{"wordgoodgoodgoodbestword"};
vector<string> words{"word","good","best","word"};
vector<int> o{};
Solution solution;
EXPECT_EQ(solution.findSubstring(s, words), o);
}