Skip to content

Commit b272ae6

Browse files
authored
Create number-of-segments-in-a-string.cpp
1 parent 7ae21a6 commit b272ae6

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int countSegments(string s) {
7+
int result = static_cast<int>(!s.empty() && s.back() != ' ');
8+
for (int i = 1; i < s.size(); ++i) {
9+
if (s[i] == ' ' && s[i - 1] != ' ') {
10+
++result;
11+
}
12+
}
13+
return result;
14+
}
15+
};

0 commit comments

Comments
 (0)