来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-segments-in-a-string/
描述
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: “Hello, my name is John”
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 “Hello,” 算作 1 个单词。
题解
内置
class Solution {
public int countSegments(String s) {
String trimmed = s.trim();
if (trimmed.equals("")) {
return 0;
}
return trimmed.split("\\s+").length;
}
}
复杂度分析
- 时间复杂度 :
。这里用到的内置函数的时间复杂度或为
,或为
,故整个算法可以在线性复杂度内完成。
空间复杂度 :
。split函数返回长度为
的数组/列表,故算法使用线性的额外空间。
原地
class Solution {
public int countSegments(String s) {
int segmentCount = 0;
for (int i = 0; i < s.length(); i++) {
if ((i == 0 || s.charAt(i-1) == ' ') && s.charAt(i) != ' ') {
segmentCount++;
}
}
return segmentCount;
}
}
复杂度分析
时间复杂度 :
。对每个下标进行常数时间的检测。
- 空间复杂度 :
。只使用了额外的几个整数,因此使用的空间为常数。