docs/algorithms/algs/016/
第 016 期(2022.1.27) | Learning
题目描述 # 句子仅由小写字母(‘a’ 到 ‘z’)、数字(‘0’ 到 ‘9’)、连字符('-')、标点符号('!'、'.' 和 ‘,')以及空格(’ ‘)组成。每个句子可以根据空格分解成 一个或者多个 token ,这些 token 之间由一个或者多个空格 ' ' 分隔。 如果一个 token 同时满足下述条件,则认为
func countValidWords(sentence string) int { words := strings.Fields(sentence) cunt := 0 CuntWord: for _, word := range words { sum := 0 n := len(word) for i := 0; i < n; i++ { if unicode.IsLetter(rune(word[i])) { continue } else if unicode.IsDigit(rune(word[i])) { continue CuntWord } else if word[i] == '-' { if sum == 1 { continue CuntWord } sum++ if i == 0 || i == n-1 || !unicode.IsLetter(rune(word[i-1])) || !unicode.IsLetter(rune(word[i+1])) { continue CuntWord break } } else if i != n-1 { continue CuntWord break } } cunt++ } return cunt }