LeetCode2047:Go语言实现句子中有效单词数统计方法
题目
句子仅由小写字母('a' 到 'z')、数字('0' 到 '9')、连字符('-')、标点符号('!'、'.' 和 ',')以及空格(' ')组成。
每个句子可以根据空格分解成 一个或者多个 token ,这些 token 之间由一个或者多个空格 ' ' 分隔。
如果一个 token 同时满足下述条件,则认为这个 token 是一个有效单词:
仅由小写字母、连字符和/或标点(不含数字)。
至多一个 连字符 '-' 。如果存在,连字符两侧应当都存在小写字母("a-b" 是一个有效单词,但 "-ab" 和 "ab-" 不是有效单词)。
至多一个 标点符号。如果存在,标点符号应当位于 token 的 末尾 。
这里给出几个有效单词的例子:"a-b."、"afad"、"ba-c"、"a!" 和 "!" 。
给你一个字符串 sentence ,请你找出并返回 sentence 中 有效单词的数目 。
示例 1:输入:sentence = "cat and dog" 输出:3
解释:句子中的有效单词是 "cat"、"and" 和 "dog"
示例 2:输入:sentence = "!this 1-s b8d!" 输出:0
解释:句子中没有有效单词
"!this" 不是有效单词,因为它以一个标点开头
"1-s" 和 "b8d" 也不是有效单词,因为它们都包含数字
示例 3:输入:sentence = "alice and bob are playing stone-game10" 输出:5
解释:句子中的有效单词是 "alice"、"and"、"bob"、"are" 和 "playing"
"stone-game10" 不是有效单词,因为它含有数字
示例 4:输入:sentence = "he bought 2 pencils, 3 erasers, and 1 pencil-sharpener." 输出:6
解释:句子中的有效单词是 "he"、"bought"、"pencils,"、"erasers,"、"and" 和 "pencil-sharpener."
提示:1 <= sentence.length <= 1000
sentence 由小写英文字母、数字(0-9)、以及字符(' '、'-'、'!'、'.' 和 ',')组成
句子中至少有 1 个 token
解题思路分析
1、遍历;时间复杂度O(n),空间复杂度O(n)
var m map[byte]bool = map[byte]bool{
'!': true,
'.': true,
',': true,
}
func countValidWords(sentence string) int {
res := 0
arr := strings.Fields(sentence)
for i := 0; i < len(arr); i++ {
flag := true
countA := 0
countB := 0
for j := 0; j < len(arr[i]); j++ {
if '0' <= arr[i][j] && arr[i][j] <= '9' {
flag = false
break
}
if m[arr[i][j]] == true {
countA++
if j != len(arr[i])-1 {
flag = false
break
}
}
if arr[i][j] == '-' {
countB++
if j == 0 || j == len(arr[i])-1 {
flag = false
break
}
if (('a' <= arr[i][j-1] && arr[i][j-1] <= 'z') &&
('a' <= arr[i][j+1] && arr[i][j+1] <= 'z')) == false {
flag = false
break
}
}
}
if flag == true && countA <= 1 && countB <= 1 {
res++
}
}
return res
}2、内置函数;时间复杂度O(n),空间复杂度O(n)
var m map[byte]bool = map[byte]bool{
'!': true,
'.': true,
',': true,
}
func countValidWords(sentence string) int {
res := 0
arr := strings.Fields(sentence)
for i := 0; i < len(arr); i++ {
temp := arr[i]
if m[temp[len(temp)-1]] == true {
temp = temp[:len(temp)-1]
}
if strings.ContainsAny(arr[i], "0123456789") ||
strings.ContainsAny(temp, "!.,") ||
strings.Count(temp, "-") >= 2 {
continue
}
j := strings.IndexByte(temp, '-')
// 存在-
if j >= 0 && (j == 0 || j == len(temp)-1 || unicode.IsLower(rune(temp[j-1])) == false ||
unicode.IsLower(rune(temp[j+1])) == false) {
continue
}
res++
}
return res
}总结
Easy题目,根据题目意思判断即可
声明:本文由"麦兜"发布,不代表"破站"立场,转载联系作者并注明出处:https://www.848586.cn/264892.html
