LeetCode 2047: Number of Valid Words in a Sentence Solution
Master LeetCode problem 2047 (Number of Valid Words in a Sentence), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2047. Number of Valid Words in a Sentence
Problem Explanation
Explanation:
To solve this problem, we need to iterate through each token in the given sentence and check if it meets the criteria to be a valid word. We can do this by applying the specified rules for a valid word: containing only lowercase letters, hyphens, and/or punctuation, having at most one hyphen surrounded by lowercase characters, and having at most one punctuation mark at the end.
We can implement the solution by splitting the sentence into tokens using spaces as delimiters. Then, for each token, we can check if it satisfies the conditions to be a valid word. If a token is a valid word, we increment a counter. Finally, we return the total count of valid words found in the sentence.
- Time complexity: O(n), where n is the length of the input sentence.
- Space complexity: O(1) as we are not using any additional data structures that grow with the input size.
:
Solution Code
class Solution {
public int countValidWords(String sentence) {
String[] tokens = sentence.split("\\s+");
int count = 0;
for (String token : tokens) {
if (isValidWord(token)) {
count++;
}
}
return count;
}
private boolean isValidWord(String word) {
if (word.isEmpty() || !Character.isLetter(word.charAt(0))) {
return false;
}
boolean hasHyphen = false;
boolean hasPunctuation = false;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (Character.isLetter(c)) {
continue;
} else if (c == '-') {
if (hasHyphen || i == 0 || i == word.length() - 1 || !Character.isLetter(word.charAt(i - 1)) || !Character.isLetter(word.charAt(i + 1))) {
return false;
}
hasHyphen = true;
} else if (i == word.length() - 1 && (c == '.' || c == '!' || c == ',')) {
hasPunctuation = true;
} else {
return false;
}
}
return !hasHyphen || hasPunctuation;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2047 (Number of Valid Words in a Sentence)?
This page provides optimized solutions for LeetCode problem 2047 (Number of Valid Words in a Sentence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2047 (Number of Valid Words in a Sentence)?
The time complexity for LeetCode 2047 (Number of Valid Words in a Sentence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2047 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2047 in Java, C++, or Python.