- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 87 lines of C++ from the credited upstream file count-valid-word-occurrences.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 6 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<int> countWordOccurrences(vector<string>& chunks, vector<string>& queries) {8 string curr;9 const auto& check = [&](int i, int j) {10 return islower(chunks[i][j]) ||11 (chunks[i][j] == '-' &&12 (!empty(curr) && islower(curr.back())) &&13 ((j + 1 < size(chunks[i]) && islower(chunks[i][j + 1])) || (j + 1 == size(chunks[i]) && i + 1 < size(chunks) && islower(chunks[i + 1][0])))14 );15 };16 17 unordered_map<string, int> cnt;18 for (int i = 0; i < size(chunks); ++i) {19 for (int j = 0; j < size(chunks[i]); ++j) {20 if (check(i, j)) {21 curr.push_back(chunks[i][j]);22 continue;23 }24 if (!empty(curr)) {25 ++cnt[curr];26 curr.clear();27 }28 }29 }30 if (!empty(curr)) {31 ++cnt[curr];32 curr.clear();33 }34 vector<int> result(size(queries));35 for (int i = 0; i < size(queries); ++i) {36 if (cnt.count(queries[i])) {37 result[i] = cnt[queries[i]];38 }39 }40 return result;41 }42};43 44454647class Solution2 {48public:49 vector<int> countWordOccurrences(vector<string>& chunks, vector<string>& queries) {50 string s;51 const auto& check = [&](int i) {52 return islower(s[i]) ||53 (s[i] == '-' &&54 (i - 1 >= 0 && islower(s[i - 1])) &&55 (i + 1 < size(s) && islower(s[i + 1]))56 );57 };58 59 for (const auto& x : chunks) {60 s += x;61 }62 string curr;63 unordered_map<string, int> cnt;64 for (int i = 0; i < size(s); ++i) {65 if (check(i)) {66 curr.push_back(s[i]);67 continue;68 }69 if (!empty(curr)) {70 ++cnt[curr];71 curr.clear();72 }73 }74 if (!empty(curr)) {75 ++cnt[curr];76 curr.clear();77 }78 vector<int> result(size(queries));79 for (int i = 0; i < size(queries); ++i) {80 if (cnt.count(queries[i])) {81 result[i] = cnt[queries[i]];82 }83 }84 return result;85 }86};87