2047. Number of Valid Words in a Sentence

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

time: O(w*c), w: number of words, c: each word's length

space: O(w)

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

Last updated