-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountValidWords.kt
More file actions
74 lines (69 loc) · 1.96 KB
/
countValidWords.kt
File metadata and controls
74 lines (69 loc) · 1.96 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Solution {
fun countValidWords(sentence: String): Int {
val n = sentence.count()
var l = 0
var r = 0
var res = 0
while (true) {
while (l < n && sentence[l] == ' ') {
l++
}
if (l >= n) {
break
}
r = l + 1
while (r < n && sentence[r] != ' ') {
r++
}
if (isValid(sentence.substring(l, r))) { // 判断根据空格分解出来的 token 是否有效
res++
}
l = r + 1
}
return res
}
fun isValid(word: String): Boolean {
val n = word.count()
var hasHyphens = false
for (i in 0 until n) {
if (Character.isDigit(word[i])) {
return false
} else if (word[i] == '-') {
if (hasHyphens == true || i == 0 || i == n - 1 || !Character.isLetter(word[i - 1]) || !Character.isLetter(
word[i + 1]
)
) {
return false
}
hasHyphens = true
} else if (word[i] == '!' || word[i] == '.' || word[i] == ',') {
if (i != n - 1) {
return false
}
}
}
return true
}
/*fun countValidWords(sentence: String): Int {
val n = sentence.length
var l = 0
var r = 0
var res = 0
while (true) {
while (l < n && sentence[l] == ' ') {
l++
}
if (l >= n) {
break
}
r = l + 1
while (r < n && sentence[r] != ' ') {
r++
}
if (isValid(sentence.substring(l, r))) { // 判断根据空格分解出来的 token 是否有效
res++
}
l = r + 1
}
return res*/
}