LeetCode in Kotlin

2047. Number of Valid Words in a Sentence

Easy

A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.

A token is a valid word if all three of the following are true:

Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".

Given a string sentence, return the number of valid words in sentence.

Example 1:

Input: sentence = “cat and dog”

Output: 3

Explanation: The valid words in the sentence are “cat”, “and”, and “dog”.

Example 2:

Input: sentence = “!this 1-s b8d!”

Output: 0

Explanation: There are no valid words in the sentence.

“!this” is invalid because it starts with a punctuation mark.

“1-s” and “b8d” are invalid because they contain digits.

Example 3:

Input: sentence = “alice and bob are playing stone-game10”

Output: 5

Explanation: The valid words in the sentence are “alice”, “and”, “bob”, “are”, and “playing”. “stone-game10” is invalid because it contains digits.

Constraints:

Solution

class Solution {
    fun countValidWords(sentence: String): Int {
        val tokens = sentence.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        var count = 0
        for (token in tokens) {
            var hyphenCount = 0
            var punctuationMarkCount = 0
            var valid = true
            if (token.isEmpty() || token == "") {
                continue
            }
            for (i in 0 until token.length) {
                if (token[i] == '-') {
                    hyphenCount++
                    if (hyphenCount > 1 || i == 0 || i == token.length - 1 ||
                        !Character.isAlphabetic(token[i - 1].code) ||
                        !Character.isAlphabetic(token[i + 1].code)
                    ) {
                        valid = false
                        break
                    }
                } else if (token[i] == '!' || token[i] == '.' || token[i] == ',') {
                    punctuationMarkCount++
                    if (punctuationMarkCount > 1 || i != token.length - 1) {
                        valid = false
                        break
                    }
                } else if (Character.isDigit(token[i])) {
                    valid = false
                    break
                }
            }
            if (valid) {
                count++
            }
        }
        return count
    }
}