434.Number of Segments in a String
Given a string s
, return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.
Example 1:
1 2 3
| Input: s = "Hello, my name is John" Output: 5 Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
|
Example 2:
1 2
| Input: s = "Hello" Output: 1
|
上锁:
时间复杂度:O(n)
空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public: int countSegments(string s) { int ans = 0; bool flag = true; for (char ch : s) { if (ch != ' ' && flag) { ans++; flag = false; } if (ch == ' ')flag = true; } return ans; } };
|
原地法:
时间复杂度:O(n)
空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public: int countSegments(string s) { int segmentCount = 0;
for (int i = 0; i < s.size(); i++) { if ((i == 0 || s[i - 1] == ' ') && s[i] != ' ') { segmentCount++; } }
return segmentCount; } };
|