Problem
题目大意:返回字符串中的非空白字符连续的字串数量。
https://leetcode.com/problems/number-of-segments-in-a-string/description/
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John" Output: 5
Solution
Be aware of special cases: like ” “.
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Solution { public: int countSegments(string s) { if (s.empty()) return 0; int ans = 0; int i = 0; while (i < s.length()) { while (i < s.length() && s[i] == ' ') ++i; if (i == s.length()) break; while (i < s.length() && s[i] != ' ') ++i; ++ans; ++i; } return ans; } }; |
Python3
1 2 3 4 5 6 7 |
""" Author: Huahua Running time: 40 ms """ class Solution: def countSegments(self, s): return len(s.split()) |