开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第 30 天,点击查看活动详情。
句子中的最多单词数
原题地址
一个 句子 由一些 单词 以及它们之间的单个空格组成,句子的开头和结尾不会有多余空格。
给你一个字符串数组 sentences
,其中 sentences[i]
表示单个 句子 。
请你返回单个句子里 单词的最多数目 。
示例 1:
输入:sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
输出:6
解释:
- 第一个句子 "alice and bob love leetcode" 总共有 5 个单词。
- 第二个句子 "i think so too" 总共有 4 个单词。
- 第三个句子 "this is great thanks very much" 总共有 6 个单词。
所以,单个句子中有最多单词数的是第三个句子,总共有 6 个单词。
示例 2:
输入:sentences = ["please wait", "continue to fight", "continue to win"]
输出:3
解释:可能有多个句子有相同单词数。
这个例子中,第二个句子和第三个句子(加粗斜体)有相同数目的单词数。
提示:
1 <= sentences.length <= 100
1 <= sentences[i].length <= 100
sentences[i]
只包含小写英文字母和 ' ' 。sentences[i]
的开头和结尾都没有空格。sentences[i]
中所有单词由单个空格隔开。
思路分析
方法一
- 定义
result
来存储每个句子中的单词长度; - 循环遍历
sentences
,然后将每个句子按照' '
使用split
进行分割,并取其长度存储到result
中; - 返回
result
中的最大值。
方法二
- 定义
result
来存储最大长度,初始值为0
; - 循环遍历
sentences
,然后将每个句子按照' '
使用split
进行分割,并取其长度跟result
进行对比,将大的那个值赋值给result
; - 循环结束后,返回
result
即可。
AC 代码
方法一
/**
* @param {string[]} sentences
* @return {number}
*/
var mostWordsFound = function(sentences) {
const result = []
for(let i = 0; i < sentences.length; i++) {
const len = sentences[i].split(' ').length
result.push(len)
}
return Math.max(...result)
};
结果:
- 执行结果: 通过
- 执行用时:72 ms, 在所有 JavaScript 提交中击败了24.44%的用户
- 内存消耗:43.3 MB, 在所有 JavaScript 提交中击败了11.66%的用户
- 通过测试用例:90 / 90
方法二
/**
* @param {string[]} sentences
* @return {number}
*/
var mostWordsFound = function(sentences) {
let result = 0
for(let i = 0; i < sentences.length; i++) {
const len = sentences[i].split(' ').length
result = Math.max(result, len)
}
return result
};
结果:
- 执行结果:通过
- 执行用时:64 ms, 在所有 JavaScript 提交中击败了71.67%的用户
- 内存消耗:43.3 MB, 在所有 JavaScript 提交中击败了13.89%的用户
- 通过测试用例:90 / 90