-
Notifications
You must be signed in to change notification settings - Fork 8
/
solution.cpp
61 lines (57 loc) · 1.2 KB
/
solution.cpp
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* 27 / 27 test cases passed.
* Runtime: 0 ms
* Memory Usage: 6 MB
*/
class Solution {
public:
int countSegments(string s) {
if (s == "") return 0;
int ans = 0;
int beg = 0, end = s.size() - 1;
while (beg < s.size() && s[beg] == ' ') beg++;
while (end >= 0 && s[end] == ' ') end--;
if (beg > end) return 0;
for (int i = beg; i <= end; i++) {
if (s[i] == ' ' && (i > 0 && s[i - 1] != ' ')) {
ans++;
}
}
return ans + 1;
}
};
/**
* 27 / 27 test cases passed.
* Runtime: 0 ms
* Memory Usage: 6.1 MB
*/
class Solution2 {
public:
int countSegments(string s) {
istringstream iss(s);
string next;
int ans = 0;
while (iss) {
iss >> next;
ans += 1;
}
return ans - 1;
}
};
/**
* 27 / 27 test cases passed.
* Runtime: 0 ms
* Memory Usage: 6.1 MB
*/
class Solution3 {
public:
int countSegments(string s) {
int ans = 0;
for (int i = 0; i < s.size(); i++) {
if ((i == 0 || s[i - 1] == ' ') && s[i] != ' ') {
ans ++;
}
}
return ans;
}
};