Skip to content

Commit d163b0c

Browse files
committed
Time: 4 ms (85.77%), Space: 44.3 MB (71.54%) - LeetHub
1 parent 1b583fb commit d163b0c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public int countValidWords(String sentence) {
3+
String[] words = sentence.split(" ");
4+
int count = 0;
5+
for (String word : words) {
6+
if (isToken(word)) {
7+
count++;
8+
}
9+
}
10+
return count;
11+
}
12+
13+
public boolean isToken(String word) {
14+
if (word.length() == 0) return false;
15+
int hyphenCount = 0;
16+
for (int i = 0; i < word.length(); i++) {
17+
char ch = word.charAt(i);
18+
if (ch >= '0' && ch <= '9') {
19+
return false;
20+
}
21+
if (ch == '-') {
22+
if (i == 0 || i == word.length() - 1 ||
23+
(i > 0 && word.charAt(i - 1) != '-' &&
24+
!Character.isLowerCase(word.charAt(i - 1))) ||
25+
(i < word.length() - 1 && !Character.isLowerCase(word.charAt(i + 1)))) {
26+
return false;
27+
}
28+
hyphenCount++;
29+
}
30+
if ((ch == '.' || ch == ',' || ch == '!') && i < word.length() - 1) {
31+
return false;
32+
}
33+
}
34+
return hyphenCount <= 1;
35+
}
36+
}

0 commit comments

Comments
 (0)