comments | difficulty | edit_url | tags | |
---|---|---|---|---|
true |
简单 |
|
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: "Hello, my name is John" 输出: 5 解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
我们将字符串
时间复杂度
class Solution:
def countSegments(self, s: str) -> int:
return len(s.split())
class Solution {
public int countSegments(String s) {
int ans = 0;
for (String t : s.split(" ")) {
if (!"".equals(t)) {
++ans;
}
}
return ans;
}
}
class Solution {
public:
int countSegments(string s) {
int ans = 0;
istringstream ss(s);
while (ss >> s) ++ans;
return ans;
}
};
func countSegments(s string) int {
ans := 0
for _, t := range strings.Split(s, " ") {
if len(t) > 0 {
ans++
}
}
return ans
}
function countSegments(s: string): number {
return s.split(/\s+/).filter(Boolean).length;
}
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;
}
}
我们也可以直接遍历字符串的每个字符
遍历结束后,返回答案即可。
时间复杂度
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 {
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 {
public:
int countSegments(string s) {
int ans = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) {
++ans;
}
}
return ans;
}
};
func countSegments(s string) int {
ans := 0
for i, c := range s {
if c != ' ' && (i == 0 || s[i-1] == ' ') {
ans++
}
}
return ans
}
function countSegments(s: string): number {
let ans = 0;
for (let i = 0; i < s.length; i++) {
let c = s[i];
if (c !== ' ' && (i === 0 || s[i - 1] === ' ')) {
ans++;
}
}
return ans;
}
class Solution {
/**
* @param String $s
* @return Integer
*/
function countSegments($s) {
$ans = 0;
$n = strlen($s);
for ($i = 0; $i < $n; $i++) {
$c = $s[$i];
if ($c !== ' ' && ($i === 0 || $s[$i - 1] === ' ')) {
$ans++;
}
}
return $ans;
}
}