-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNumberOfValidWordsInASentence.java
69 lines (60 loc) · 1.91 KB
/
NumberOfValidWordsInASentence.java
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
package com.smlnskgmail.jaman.leetcodejava.easy;
// https://leetcode.com/problems/number-of-valid-words-in-a-sentence/
public class NumberOfValidWordsInASentence {
private final String input;
public NumberOfValidWordsInASentence(String input) {
this.input = input;
}
public int solution() {
int result = 0;
for (String word : input.split("\\s+")) {
if (word.isEmpty()) {
continue;
}
if (checkFirstRule(word) && checkSecondRule(word) && checkThirdRule(word)) {
result++;
}
}
return result;
}
private boolean checkFirstRule(String token) {
for (int i = 0; i < token.length(); i++) {
char curr = token.charAt(i);
if (Character.isDigit(curr)
|| (Character.isLetter(curr) && Character.isUpperCase(curr))) {
return false;
}
}
return true;
}
private boolean checkSecondRule(String token) {
int n = token.length();
int count = 0;
for (int i = 0; i < n; i++) {
if (token.charAt(i) == '-') {
count++;
if (count > 1) {
break;
}
if (i == 0 || i == n - 1) {
return false;
}
if (!Character.isLetter(token.charAt(i - 1))
|| !Character.isLetter(token.charAt(i + 1))) {
return false;
}
}
}
return count < 2;
}
private boolean checkThirdRule(String token) {
for (int i = 0; i < token.length() - 1; i++) {
char curr = token.charAt(i);
if (!Character.isLetter(curr)
&& !Character.isDigit(curr) && curr != '-') {
return false;
}
}
return true;
}
}