#2047
Easy Algorithms Number of valid words in a sentence
String
31.0% acceptance
Feb 25, 2026
352
827
A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.
A token is a valid word if all three of the following are true:
It only contains lowercase letters, hyphens, and/or punctuation (no digits).
There is at most one hyphen '-'. If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid).
There is at most one punctuation mark. If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid).
Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".
Given a string sentence, return the number of valid words in sentence.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn count_valid_words(sentence: String) -> i32 {
sentence.split_whitespace().filter(|&t| Self::is_valid(t)).count() as i32
}
fn is_valid(token: &str) -> bool {
let chars: Vec<char> = token.chars().collect();
let n = chars.len();
let mut hyphen = 0;
let mut punct = 0;
for (i, &c) in chars.iter().enumerate() {
if c.is_ascii_digit() {
return false;
}
if c == '-' {
hyphen += 1;
if hyphen > 1 || i == 0 || i == n - 1 {
return false;
}
if !chars[i - 1].is_ascii_lowercase() || !chars[i + 1].is_ascii_lowercase() {
return false;
}
}
if matches!(c, '!' | '.' | ',') {
punct += 1;
if punct > 1 || i != n - 1 {
return false;
}
}
}
true
}
}