2047_句子中的有效单词数

难度:简单

题目

句子仅由小写字母('a''z')、数字('0' '9')、连字符('-')、标点符号('!''.'',')以及空格(' ')组成。每个句子可以根据空格分解成 一个或者多个 token ,这些 token 之间由一个或者多个空格 ' ' 分隔。

如果一个 token 同时满足下述条件,则认为这个 token 是一个有效单词:

仅由小写字母、连字符和/或标点(不含数字)。
至多一个 连字符 '-' 。如果存在,连字符两侧应当都存在小写字母("a-b" 是一个有效单词,但 "-ab""ab-" 不是有效单词)。
至多一个 标点符号。如果存在,标点符号应当位于 token 的 末尾 。
这里给出几个有效单词的例子:"a-b.""afad""ba-c""a!""!"

给你一个字符串 sentence ,请你找出并返回 sentence 中 有效单词的数目 。

示例

示例一:

输入:sentence = “cat and dog”
输出:3
解释:句子中的有效单词是 “cat”、”and” 和 “dog”

示例二:

输入:sentence = “!this 1-s b8d!”
输出:0
解释:句子中没有有效单词
“!this” 不是有效单词,因为它以一个标点开头
“1-s” 和 “b8d” 也不是有效单词,因为它们都包含数字

示例三:

输入:sentence = “alice and bob are playing stone-game10”
输出:5
解释:句子中的有效单词是 “alice”、”and”、”bob”、”are” 和 “playing”
“stone-game10” 不是有效单词,因为它含有数字

示例四:

输入: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
2
3
4
5
6
7
8
9
10
11
12
13
14
while (true){
while (left<n&&sentence.charAt(left)==' '){
left++;
}
if (left>=n) break;
right = left+1;
while (right <n&&sentence.charAt(right)!=' '){
right++;
}
if (isValidWord(sentence.substring(left,right))){
ans++;
}
left = right + 1;
}

然后判断单词是否有效。根据题目,单词有效的条件有三个:

  1. 不能有数字
  2. 标点符号只能存在于单词结尾,且只能有一个
  3. 连字符最多只有一个,且连字符两端为小写字母
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static boolean isValidWord(String word){
int n = word.length();
boolean flag = false;
for(int i=0; i<n;i++){
if (word.charAt(i)>='0'&&word.charAt(i)<='9'){
// 判定为数字
return false;
} else if (word.charAt(i)==','||word.charAt(i)=='.'||word.charAt(i)=='!'){
// 判定标点符号位置
if (i!=n-1){
return false;
}
} else if (word.charAt(i)=='-'){
// 判定是否有多个连字符,判定连字符位置(不能是0和n-1),判定连字符两端是否为字母
if (flag||i==0||i==n-1||!Character.isLetter(word.charAt(i-1))||!Character.isLetter(word.charAt(i+1))){
return false;
}
flag = true;
}
}
return true;
}

汇总起来即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public int countValidWords(String sentence) {
int ans = 0,left=0,right=0;
int n = sentence.length();
while (true){
while (left<n&&sentence.charAt(left)==' '){
left++;
}
if (left>= n) break;
right = left+1;
while (right<n&&sentence.charAt(right)!=' '){
right++;
}
if(isValidWord(sentence.substring(left,right))){
ans++;
}
left = right + 1;
}
return ans;
}
public boolean isValidWord(String word){
int n = word.length();
boolean flag = false;
for(int i=0; i<n;i++){
if (word.charAt(i)>='0'&&word.charAt(i)<='9'){
// 判定为数字
return false;
} else if (word.charAt(i)==','||word.charAt(i)=='.'||word.charAt(i)=='!'){
if (i!=n-1){
return false;
}
} else if (word.charAt(i)=='-'){
if (flag||i==0||i==n-1||!Character.isLetter(word.charAt(i-1))||!Character.isLetter(word.charAt(i+1))){
return false;
}
flag = true;
}
}
return true;
}