434. 字符串中的单词数

转载自Leet Code

题目描述

统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。 请注意,你可以假定字符串里不包括任何不可打印的字符。

示例: >输入:"Hello, my name is John" >输出:5 >解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。


我的代码

\(T(N) = O(N)\), \(S(N) = O(1)\)

{.line-numbers}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class MySolution434 
{
public int countSegments(String s)
{
if (s==null||s.length()<=0) return 0;
int count = 0;
boolean inBlank = false;

if (s.charAt(0)!=' ') count++;
for (char ch:s.toCharArray())
{
if (ch==' '&&!inBlank)
{
inBlank = true; continue;
}
else if (ch==' '&&inBlank) continue;
else if (ch!=' '&&inBlank)
{
inBlank = false; count++; continue;
}
else if (ch!=' '&&!inBlank) continue;
}
return count;
}
}

方法:使用语言的内置函数

\(T(N) = O(N)\), \(S(N) = O(N)\)

执行效率不如代码可读性重要的情况下,使用语言内置的函数解决问题更好些。

在Java中会需要考虑一些边缘情况: 首先,开头的一个或多个空格会导致split函数在字符串的开头产生一个错误的"",因此我们使用内置的trim函数来移除这些空格; 其次,如果结果为空串的情况下,可以直接返回0。 由于split函数的下述特性,这一点很重要:

String[] tokens = "".split("\s++"); tokens.length; // 1 tokens[0]; // ""

当抵达最后的 return 语句,我们将trim过的字符串以一个或多个空格字符切分(split 函数可以使用正则表达式),并返回结果数组的长度。


代码

{.line-numbers}
1
2
3
4
5
6
7
8
9
10
class Solution434 
{
public int countSegments(String s)
{
String trimmed = s.trim(); // trim() 方法用于删除字符串的头尾空白符。
if (trimmed.equals("")) return 0;

return trimmed.split("\\s+").length;
}
}