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
Many programming languages provide the inbuilt string split function that allows you to split a string into array of strings by a set of delimiters. For example, using Python3, you can solve this problem by the following code:
1 2 3 4 5 6 7 8 9 10 | import re class Solution: def countSegments(self, s): """ :type s: str :rtype: int """ s = re.sub(" +", " ", s).strip() return len(s.split(" ")) if s != '' else 0 |
import re class Solution: def countSegments(self, s): """ :type s: str :rtype: int """ s = re.sub(" +", " ", s).strip() return len(s.split(" ")) if s != '' else 0
The re.sub(” +”, ” “, s) uses the regular expression tool to remove extra white spaces in the string. Then we just need to use split to group into segments. The edge case is when the string is empty, which should return 0 segments instead.
C++ Implementation of Counting Segments
We can scan the string from the beginning, if we meet a non-white space character and its previous character is white space, then we find a segment. O(n) complexity and constant space.
1 2 3 4 5 6 7 8 9 10 11 12 | class Solution { public: int countSegments(string s) { auto cnt = 0; for (int i = 0; i < s.size(); ++ i) { if (((i == 0) || (s[i - 1] == ' ')) && (s[i] != ' ')) { cnt ++; } } return cnt; } }; |
class Solution { public: int countSegments(string s) { auto cnt = 0; for (int i = 0; i < s.size(); ++ i) { if (((i == 0) || (s[i - 1] == ' ')) && (s[i] != ' ')) { cnt ++; } } return cnt; } };
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: C++ Coding Exercise - Subdomain Visit Count
Next Post: How to Find Largest Triangle Area using Shoelace Formula?