forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_2047.java
43 lines (42 loc) · 1.71 KB
/
_2047.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
package com.fishercoder.solutions;
public class _2047 {
public static class Solution1 {
public int countValidWords(String sentence) {
String[] tokens = sentence.split("\\s+");
int count = 0;
for (String token : tokens) {
int hyphenCount = 0;
int punctuationMarkCount = 0;
boolean valid = true;
if (token.isEmpty() || token.equals("") || token.length() == 0) {
continue;
}
for (int i = 0; i < token.length(); i++) {
if (token.charAt(i) == '-') {
hyphenCount++;
if (hyphenCount > 1 || i == 0 || i == token.length() - 1 || !Character.isAlphabetic(token.charAt(i - 1)) || !Character.isAlphabetic(token.charAt(i + 1))) {
valid = false;
break;
}
} else if (token.charAt(i) == '!' || token.charAt(i) == '.' || token.charAt(i) == ',') {
punctuationMarkCount++;
if (punctuationMarkCount > 1 || i != token.length() - 1) {
valid = false;
break;
}
} else if (Character.isDigit(token.charAt(i))) {
valid = false;
break;
} else if (Character.isDigit(token.charAt(i))) {
valid = false;
break;
}
}
if (valid) {
count++;
}
}
return count;
}
}
}