# 2047. Number of Valid Words in a Sentence

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2FBzjiItmDkVjdB3Ltmi0Z%2F%E5%9C%96%E7%89%87.png?alt=media\&token=d7cee4c7-5729-4f53-93d5-bdd60b11904f)

other constraint see link: [https://leetcode.com/problems/number-of-valid-words-in-a-sentence/](https://leetcode.com/problems/number-of-valid-words-in-a-sentence/)



time: O(w\*c), w: number of words, c: each word's length&#x20;

space: O(w)

```java
class Solution {
    public int countValidWords(String sentence) {
        String[] str = sentence.split(" ");
        int count = 0;
        for (String s : str) {
            s = s.trim();
            if (s.length() > 0 && isValid(s)) {
                count++;
            }
        }
        return count;
    }
    
    private boolean isValid(String s) {
        
        int hCount = 0;
        int puncCount = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                return false;
            }
            if (c == '-') {
                hCount++;
                if (i == 0 || i == s.length()-1 || hCount == 2) {
                    return false;
                }
                if (i - 1 >= 0 && !Character.isLetter(s.charAt(i-1))) {
                    return false;
                }
                if (i + 1 < s.length() && !Character.isLetter(s.charAt(i+1))) {
                    return false;
                }
            }
            
            if ((c == '!' || c == '.' || c == ',')) {
                puncCount++;
                if (i != s.length()-1 || puncCount == 2) {
                    return false;
                }
            }
        
        }
        return true;
    }
}
```

