Skip to content

Commit ea8c324

Browse files
authored
Create number-of-valid-words-in-a-sentence.cpp
1 parent 9cdccd8 commit ea8c324

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int countValidWords(string sentence) {
7+
int result = 0, token = 0, hyphen = 0;
8+
for (int i = 0; i <= size(sentence); ++i) {
9+
if (i == size(sentence) || sentence[i] == ' ') {
10+
if (token == 1) {
11+
++result;
12+
}
13+
token = hyphen = 0;
14+
continue;
15+
}
16+
if (isdigit(sentence[i]) ||
17+
(string("!.,").find(sentence[i]) != string::npos && !(i == size(sentence) - 1 || sentence[i + 1] == ' ')) ||
18+
(sentence[i] == '-' && !(hyphen == 0 && 0 < i && i < size(sentence) && isalpha(sentence[i - 1]) && isalpha(sentence[i + 1])))) {
19+
token = -1;
20+
continue;
21+
}
22+
if (token == 0) {
23+
token = 1;
24+
}
25+
if (sentence[i] == '-') {
26+
hyphen = 1;
27+
}
28+
}
29+
return result;
30+
}
31+
};

0 commit comments

Comments
 (0)