Skip to content

Commit c85ec16

Browse files
authored
Create number-of-valid-words-in-a-sentence.py
1 parent edfc0c4 commit c85ec16

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def countValidWords(self, sentence):
6+
"""
7+
:type sentence: str
8+
:rtype: int
9+
"""
10+
result = token = hyphen = 0
11+
for i in xrange(len(sentence)+1):
12+
if i == len(sentence) or sentence[i] == ' ':
13+
if token == 1:
14+
result += 1
15+
token = hyphen = 0
16+
continue
17+
if sentence[i].isdigit() or \
18+
(sentence[i] in '!.,' and not (i == len(sentence)-1 or sentence[i+1] == ' ')) or \
19+
(sentence[i] == '-' and not (hyphen == 0 and 0 < i < len(sentence)-1 and sentence[i-1].isalpha() and sentence[i+1].isalpha())):
20+
token = -1
21+
continue
22+
if token == 0:
23+
token = 1
24+
if sentence[i] == '-':
25+
hyphen = 1
26+
return result

0 commit comments

Comments
 (0)