s0030
This commit is contained in:
parent
9f4193858f
commit
8901afccf4
15
include/s0030_substring_with_concatenation_of_all_words.hpp
Normal file
15
include/s0030_substring_with_concatenation_of_all_words.hpp
Normal 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
|
33
src/s0030_substring_with_concatenation_of_all_words.cpp
Normal file
33
src/s0030_substring_with_concatenation_of_all_words.cpp
Normal 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;
|
||||||
|
}
|
19
tests/s0030_substring_with_concatenation_of_all_words.cpp
Normal file
19
tests/s0030_substring_with_concatenation_of_all_words.cpp
Normal 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);
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user