We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent edfc0c4 commit c85ec16Copy full SHA for c85ec16
Python/number-of-valid-words-in-a-sentence.py
@@ -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
22
+ if token == 0:
23
+ token = 1
24
+ if sentence[i] == '-':
25
+ hyphen = 1
26
+ return result
0 commit comments