|
| 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