Leetcode 2047: Number of Valid Words in a Sentence

grid47
grid47
Exploring patterns and algorithms
Apr 16, 2024 7 min read

A sentence consists of lowercase letters (‘a’ to ‘z’), digits (‘0’ to ‘9’), hyphens (’-’), punctuation marks (’!’, ‘.’, and ‘,’), and spaces (’ ‘) only. A token is any sequence of characters separated by spaces. A token is considered a valid word if all the following conditions are met:

  1. It does not contain any digits.
  2. It contains at most one hyphen (’-’), and if present, the hyphen must be surrounded by lowercase letters.
  3. It contains at most one punctuation mark, and if present, the punctuation mark must be at the end of the token.

Given a sentence, count the number of tokens that are valid words.

Problem
Approach
Steps
Complexity
Input: A string `sentence` consisting of lowercase English letters, digits, spaces, hyphens, and punctuation marks.
Example: Input: sentence = "hello world! test-case 1234, valid-word."
Constraints:
• 1 <= sentence.length <= 1000
• sentence contains at least one token.
• Sentence characters are limited to 'a'-'z', '0'-'9', '-', '!', '.', ',', and ' '.
Output: An integer representing the count of valid words in the sentence.
Example: Output: 2
Constraints:
• The output is always a non-negative integer.
Goal: Determine the number of valid words in the given sentence.
Steps:
• Split the sentence into tokens based on spaces.
• For each token, check if it satisfies the conditions for being a valid word.
• Count the tokens that are valid words.
Goal: Ensure all conditions for valid words are met during processing.
Steps:
• No digits are allowed in a valid word.
• At most one hyphen is allowed, and it must be surrounded by letters.
• At most one punctuation mark is allowed, and it must appear at the end of the word.
Assumptions:
• The input sentence always contains at least one token.
• Characters are limited to the defined set of letters, digits, and special characters.
Input: Input: sentence = "word1 -a invalid! valid-word."
Explanation: The valid words are "valid-word.". Other tokens fail due to digits, improper hyphen usage, or invalid punctuation placement. Output: 1.

Input: Input: sentence = "a-b test valid! example."
Explanation: The valid words are "a-b", "test", "valid!", and "example.". Output: 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus