https://leetcode.com/problems/number-of-valid-words-in-a-sentence/



Runtime: 149 ms, faster than 21.43% of TypeScript online submissions for Number of Valid Words in a Sentence.

Memory Usage: 48.6 MB, less than 21.43% of TypeScript online submissions for Number of Valid Words in a Sentence.



```typescript
function countValidWords(sentence: string): number {
    //8:04
    let words = []
    for (const word of sentence.split(" ")) {
        if (word.trim() == "") {
            continue
        }
        
        let flag = true
        
        // only contains lowercase letters
        if (word.toLowerCase() != word) {
            flag = false
        } else {
            if (/\d/.test(word)) {
                flag = false
            }
        }
        
        // at most one '-'
        const theCharFrequency = word.split("-").length - 1
        if (theCharFrequency > 1) {
            flag = false
        } else if (theCharFrequency == 1) {
            if (word.startsWith('-')) {
                flag = false
            }
            if (word.endsWith('-')) {
                flag = false
            }
        }
        
        // one punctuation
        const theFrequency1 = word.split(".").length - 1
        const theFrequency2 = word.split(",").length - 1
        const theFrequency3 = word.split("!").length - 1
        const frequencySum = theFrequency1 + theFrequency2 + theFrequency3
        if (frequencySum > 1) {
            flag= false
        } else if (frequencySum == 1) {
            if ((!word.endsWith('.') && (!word.endsWith(',')) && (!word.endsWith('!')))) {
                flag = false
            } else {
                if (word.length > 1) {
                    const aChar = word.substr(word.length-2, word.length-2);
                    if (aChar == '-') {
                        flag = false
                    }
                }
            }
        }
        
        if (flag) {
            //console.log(word)
            words.push(word)
        }
    }
    
    return words.length
    //8:14
    //debug until 8:32, the 'k-,' is also wrong
};
```
