File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
2047-number-of-valid-words-in-a-sentence Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments