Skip to main content
Back to problems
#3926
Medium Algorithms

Count valid word occurrences

45.2% acceptance
May 13, 2026
33
42
You are given an array of strings chunks. The strings are concatenated in order to form a single string s. You are also given an array of strings queries. A word is defined as a substring of s that: consists of lowercase English letters ('a' to 'z'), may include hyphens ('-') only if each hyphen is surrounded by lowercase English letters, and is not part of a longer substring that also satisfies the above conditions. Any character that is not a lowercase English letter or a valid hyphen acts as a separator. Return an integer array ans such that ans[i] is the number of occurrences of queries[i] as a word in s. A substring is a contiguous non-empty sequence of characters within a string.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn count_word_occurrences(chunks: Vec<String>, queries: Vec<String>) -> Vec<i32> {
    use std::collections::HashMap;
    let s: String = chunks.concat();
    let bytes = s.as_bytes();
    let n = bytes.len();
    let mut words: HashMap<String, i32> = HashMap::new();
    let mut i = 0;
    while i < n {
      if !bytes[i].is_ascii_lowercase() {
        i += 1;
        continue;
      }
      let start = i;
      i += 1;
      loop {
        if i >= n { break; }
        let c = bytes[i];
        if c.is_ascii_lowercase() {
          i += 1;
        } else if c == b'-' && i + 1 < n && bytes[i + 1].is_ascii_lowercase() {
          i += 2;
        } else {
          break;
        }
      }
      let word = std::str::from_utf8(&bytes[start..i]).unwrap().to_string();
      *words.entry(word).or_insert(0) += 1;
    }
    queries.into_iter()
      .map(|q| *words.get(&q).unwrap_or(&0))
      .collect()
  }
}