Problem Description
You are given a string s consisting of several words separated by some space characters before and after them. Returns the length of the last word in the string.
A word is the largest substring consisting of only letters and not containing any space characters.
Example 1:
输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。
Example 2:
输入:s = " fly me to the moon "
输出:4
解释:最后一个单词是“moon”,长度为4。
Example 3:
输入:s = "luffy is still joyboy"
输出:6
解释:最后一个单词是长度为6的“joyboy”。
Leetcode original title address: https://leetcode.cn/problems/length-of-last-word
solution
Scheme 1 to remove spaces and add spaces to flashback the traversal count
Because the problem is to find the length of the last word, it is necessary to traverse in flashback, and then a letter word appears, and a number is recorded. When a space is encountered, it indicates the end of the word (just in case, manually add a space to the far left of the word)
var lengthOfLastWord = function (s) {
// 1. 先把左右空格都去掉,再手动添加一个左空格。之所以添加左空格是因为遍历到空格时,就停止遍历
s = ' ' + s.trimEnd() // 2. 遍历到空格时候,说明一个单词正好完成了
let n = 0 // 3. 定义一个n用来统计次数
for (let i = s.length - 1; i >= 0; i--) { // 4. 因为求最后一个单词的长度,所以倒叙遍历即可。注意i要>=0,只>0就会少统计一次
if (s[i] == ' ') { // 5. 若是遇到空格了,就直接返回已统计好的次数,即:单词的长度
return n
} else { // 6. 没遇到空格说明是单词,那么就统计单词的词个数
n = n + 1
}
}
};
Solution 2: Remove spaces and convert the array, and get the length of the last item
Remove the spaces and turn the array, and get the length of the last item, the last item is the last word
var lengthOfLastWord = function (s) {
s = s.trim().split(' ') // 1. 去空格,并按照空格把字符串转成数组
return s.at(-1).length // 2. 获取数组的最后一项(即倒数第一项),即为最后一个单词
};
Array of Array.prototype.at()
method review
Usually we get the value of the last item of the array, which is usually written like this:
let arr = ['aaa','bbb','ccc']
arr[arr.length - 1] // 'ccc'
But at()
the method will actually be more convenient
at()
method takes an integer value and returns the item at that index, positive and negative numbers are allowed. Negative integers count down from the last item in the array. array[0]
will return the first item. However, for later items, do not use array.length, for example, for the last item, you can call array.at(-1)
so:
let arr = ['aaa','bbb','ccc']
arr.at(-1) // 'ccc'
Array.prototype.at()
Official Documentation:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/at
However at
method is only applicable to value, and cannot be changed by assignment...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。