[LeetCode] Count Valid Word Occurrences

3926. Count Valid Word Occurrences

You are given an array of strings chunks. Concatenate all strings in chunks in order to form a string s.

You are also given an array of strings queries.

A joiner hyphen is a hyphen character '-' in s whose previous and next characters both exist and are lowercase English letters.

A word is a maximal substring of s consisting only of lowercase English letters and joiner hyphens.

All other characters, including spaces and hyphens that are not joiner hyphens, are treated as separators.

Return an integer array ans, where ans[i] is the number of times queries[i] appears as a word in s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
vector<int> countWordOccurrences(vector<string>& chunks, vector<string>& queries) {
string s = "";
unordered_map<string,int> freq;
for(auto& chunk : chunks) {
for(auto& ch : chunk) {
if(isalpha(ch)) s.push_back(ch);
else if(ch == '-') {
if(s == "") continue;
if(s.back() == '-') {
s.pop_back();
freq[s]++;
s = "";
} else s.push_back(ch);
}
else {

if(s != "") {
if(s.back() == '-') s.pop_back();
freq[s]++;
s = "";
}
}
}
}
if(s != "") {
if(s.back() == '-') s.pop_back();
freq[s]++;
s = "";
}
vector<int> res;
for(auto& q : queries) res.push_back(freq[q]);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/count-valid-word-occurrences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.