A word is considered valid if:
You are given a string word.
Return true if word is valid, otherwise, return false.
Notes:
'a', 'e', 'i', 'o', 'u', and their uppercases are vowels.
Example 1:
Input: word = "234Adas"
Output: true
Explanation:
This word satisfies the conditions.
Example 2:
Input: word = "b3"
Output: false
Explanation:
The length of this word is fewer than 3, and does not have a vowel.
Example 3:
Input: word = "a3$e"
Output: false
Explanation:
This word contains a '$' character and does not have a consonant.
Constraints:
1 <= word.length <= 20word consists of English uppercase and lowercase letters, digits, '@', '#', and '$'.In this method, we iterate through each character of the word to check for validity. We utilize flags to confirm the presence of at least one vowel and one consonant while ensuring all characters are either letters or digits. The function will early exit if conditions for a valid word are met within the iteration.
This C function checks if the word is valid by iterating over each character. It uses strlen to check the length, strchr to identify vowels, isdigit, and isalpha from the C standard library to check each character's type. If the word is less than 3 characters or contains a non-alphanumeric character, it returns false. Otherwise, it maintains flags to check for both vowels and consonants.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n represents the total number of characters in the word.
Space Complexity: O(1), as it uses a fixed amount of extra space for flag variables.
This method enhances performance by exiting the loop as soon as the necessary conditions for a valid word are identified. By bundling multiple checks, this approach minimizes unnecessary operations and provides rapid results.
In this optimized C function, character checks are grouped logically to ensure minimal iterations. The presence of both vowels and consonants ends the loop early. Using strchr assists in direct checks for vowels.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), with n as the character count in the word, but may exit earlier.
Space Complexity: O(1), with minimal storage requirements for conditions checks.
| Approach | Complexity |
|---|---|
| Iterative Character Check | Time Complexity: O(n), where n represents the total number of characters in the word. Space Complexity: O(1), as it uses a fixed amount of extra space for flag variables. |
| Optimized Early Exit | Time Complexity: O(n), with n as the character count in the word, but may exit earlier. Space Complexity: O(1), with minimal storage requirements for conditions checks. |
Word Break - Dynamic Programming - Leetcode 139 - Python • NeetCode • 345,873 views views
Watch 9 more video solutions →Practice Valid Word with our built-in code editor and test cases.
Practice on FleetCode