Skip to content

Commit 1988fbb

Browse files
committedJan 2, 2022
Add solution #2047
1 parent 48da830 commit 1988fbb

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@
216216
2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy|
217217
2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy|
218218
2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy|
219+
2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy|
219220

220221
## License
221222

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 2047. Number of Valid Words in a Sentence
3+
* https://leetcode.com/problems/number-of-valid-words-in-a-sentence/
4+
* Difficulty: Easy
5+
*
6+
* A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'),
7+
* hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only.
8+
* Each sentence can be broken down into one or more tokens separated by one or
9+
* more spaces ' '.
10+
*
11+
* A token is a valid word if all three of the following are true:
12+
* - It only contains lowercase letters, hyphens, and/or punctuation (no digits).
13+
* - There is at most one hyphen '-'. If present, it must be surrounded by lowercase
14+
* characters ("a-b" is valid, but "-ab" and "ab-" are not valid).
15+
* - There is at most one punctuation mark. If present, it must be at the end of
16+
* the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid).
17+
*
18+
* Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".
19+
*
20+
* Given a string sentence, return the number of valid words in sentence.
21+
*/
22+
23+
/**
24+
* @param {string} sentence
25+
* @return {number}
26+
*/
27+
var countValidWords = function(sentence) {
28+
return sentence.trim().split(/\s+/).reduce((total, str) => {
29+
return total + (/^(?:([a-z]+\-?[a-z]+)|([a-z+]))?[!.,]?$/.test(str) ? 1 : 0);
30+
}, 0);
31+
};

0 commit comments

Comments
 (0)
Please sign in to comment.