2047. Number of Valid Words in a Sentence Easy
1/**
2 * [2047] Number of Valid Words in a Sentence
3 *
4 * 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 ' '.
5 * A token is a valid word if all three of the following are true:
6 *
7 * It only contains lowercase letters, hyphens, and/or punctuation (no digits).
8 * 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).
9 * 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).
10 *
11 * Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".
12 * Given a string sentence, return the number of valid words in sentence.
13 *
14 * Example 1:
15 *
16 * Input: sentence = "<u>cat</u> <u>and</u> <u>dog</u>"
17 * Output: 3
18 * Explanation: The valid words in the sentence are "cat", "and", and "dog".
19 *
20 * Example 2:
21 *
22 * Input: sentence = "!this 1-s b8d!"
23 * Output: 0
24 * Explanation: There are no valid words in the sentence.
25 * "!this" is invalid because it starts with a punctuation mark.
26 * "1-s" and "b8d" are invalid because they contain digits.
27 *
28 * Example 3:
29 *
30 * Input: sentence = "<u>alice</u> <u>and</u> <u>bob</u> <u>are</u> <u>playing</u> stone-game10"
31 * Output: 5
32 * Explanation: The valid words in the sentence are "alice", "and", "bob", "are", and "playing".
33 * "stone-game10" is invalid because it contains digits.
34 *
35 *
36 * Constraints:
37 *
38 * 1 <= sentence.length <= 1000
39 * sentence only contains lowercase English letters, digits, ' ', '-', '!', '.', and ','.
40 * There will be at least 1 token.
41 *
42 */
43pub struct Solution {}
44
45// problem: https://leetcode.com/problems/number-of-valid-words-in-a-sentence/
46// discuss: https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/?currentPage=1&orderBy=most_votes&query=
47
48// submission codes start here
49
50impl Solution {
51 pub fn count_valid_words(sentence: String) -> i32 {
52 0
53 }
54}
55
56// submission codes end
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn test_2047() {
64 }
65}
66
Back
© 2025 bowen.ge All Rights Reserved.