##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/434.html

# 434. 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.

Example:

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

## Key 1: Brute Force

class Solution {
public:
int countSegments(string s) {
int n = s.size(), cnt = 0, i = 0;
while (i < n) {
while (i < n && s[i] == ' ') ++i;
if (i < n) ++cnt;
while (i < n && s[i] != ' ') ++i;
}
return cnt;
}
};

## Key 2: Brute Force

Note: &&的优先级高于||

class Solution {
public:
int countSegments(string s) {
int cnt = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) ++cnt;
}
return cnt;
}
};

## Key 3: stringstream

stringstream读取string时默认会跳过空格.

class Solution {
public:
int countSegments(string s) {
int cnt = 0;
string word;
stringstream ss(s);
while (ss >> word) ++cnt;
return cnt;
}
};
• class Solution {
public int countSegments(String s) {
if (s == null)
return 0;
s = s.trim();
while (s.indexOf("  ") >= 0)
s = s.replaceAll("  ", " ");
int length = s.length();
if (length == 0)
return 0;
int segments = 1;
for (int i = 0; i < length; i++) {
if (s.charAt(i) == ' ')
segments++;
}
return segments;
}
}

############

class Solution {
public int countSegments(String s) {
int ans = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
++ans;
}
}
return ans;
}
}

• class Solution:
def countSegments(self, s: str) -> int:
ans = 0
for i, c in enumerate(s):
if c != ' ' and (i == 0 or s[i - 1] == ' '):
ans += 1
return ans

############

class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split())

• func countSegments(s string) int {
ans := 0
for i, c := range s {
if c != ' ' && (i == 0 || s[i-1] == ' ') {
ans++
}
}
return ans
}

• class Solution {
/**
* @param String $s * @return Integer */ function countSegments($s) {
$arr = explode(" ",$s);
$cnt = 0; for ($i = 0; $i < count($arr); $i++) { if (strlen($arr[$i]) != 0)$cnt++;
}
return \$cnt;
}
}