434.字符串中的单词数
链接:434.字符串中的单词数
难度:Easy
标签:字符串
简介:统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
题解 1 - typescript
- 编辑时间:2021-10-07
- 执行用时:80ms
- 内存消耗:39.1MB
- 编程语言:typescript
- 解法介绍:分割。
function countSegments(s: string): number {
return s.split(' ').filter(v => v.length).length;
}
题解 2 - typescript
- 编辑时间:2021-10-07
- 执行用时:72ms
- 内存消耗:39.5MB
- 编程语言:typescript
- 解法介绍:遍历。
function countSegments(s: string): number {
let ans = 0;
let f = false;
for (const c of s) {
if (c === ' ') {
if (f) {
ans++;
f = false;
}
f = false;
} else {
f = true;
}
}
if (f) ans++;
return ans;
}