434. Number of Segments in a String

  • 37.1%

https://leetcode.com/problems/number-of-segments-in-a-string/

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.

1
2
3
4
Example:

Input: "Hello, my name is John"
Output: 5

cpp

https://discuss.leetcode.com/topic/70736/one-liners

6ms, 0.00%, Dec.30, 2016

1
2
3
4
5
6
class Solution {
public:
int countSegments(string s) {
return regex_replace(regex_replace(s, regex("\\S+"), "x"), regex(" "), "").size();
}
};

https://discuss.leetcode.com/topic/70640/o-n-sentinel-value-concise-solution-c

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int countSegments(string s) {
int res = 0;
s.push_back(' ');
for(int i=1; i<s.size(); ++i)
if(s[i]==' ' && s[i-1]!=' ')
++res;
return res;
}
};

https://discuss.leetcode.com/topic/70651/c-concise-three-line-solutions

1
2
3
4
5
6
7
8
9
class Solution {
public:
int countSegments(string s) {
int res = 0;
for(int i=0; i<s.size(); i++)
res += s[i] != ' ' && (i+1 == s.size() || s[i+1]==' ');
return res;
}
};

python

https://discuss.leetcode.com/topic/70736/one-liners

1
2
3
4
5
6
7
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split())

my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
# return len(s.split())

cnt = 0
for i, char in enumerate(s):
if char != ' ' and (i==0 or s[i-1] == ' '):
cnt += 1
return cnt

java

https://discuss.leetcode.com/topic/70642/clean-java-solution-o-n

Time complexity: O(n)

Space complexity: O(1)

1
2
3
4
5
6
7
8
9
public class Solution {
public int countSegments(String s) {
int res = 0;
for(int i=0; i<s.length(); i++)
if(s.charAt(i) != ' ' && (i==0 || s.charAt(i-1)==' '))
res++;
return res;
}
}

https://discuss.leetcode.com/topic/70736/one-liners

1
2
3
4
5
public class Solution {
public int countSegments(String s) {
return ("x " + s).split(" +").length - 1;
}
}
谢谢你,可爱的朋友。