Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
給予一個有文字與空格的s字串,回傳最後字串的文字長度。 單字是由非空格組成之字串。
Example 1:
Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" with length 6.
Solution:
1. 運用.trim()移除字串中,字首前、字尾後的空白。
2. 使用.split(‘ ‘)來將字串以空白做切割為陣列。
3. 注意陣列與數列的關係。
ex.
word = [a, b, c]
array 0 1 2
Code:
var lengthOfLastWord = function(s) { const arr = s.trim().split(' ') return arr[arr.length - 1].length };
FlowChart:
Example 1
step.1 string 1 2 arr = ['Hello', 'World'] array 0 1 arr.length = 2 return arr[arr.length - 1].length //arr[1].length => 'World'.length => 5
Example 2
step.2 string 1 2 3 4 5 6 7 8 9 arr = ['fly', 'me', '', '', 'to', '', '', 'the', 'moon'] array 0 1 2 3 4 5 6 7 8 arr.length = 9 return arr[arr.length - 1].length //arr[8].length => 'moon'.length => 4
Example 3
step.3 string 1 2 3 4 arr = ['luffy', 'is', 'still', 'joyboy'] array 0 1 2 3 arr.length = 4 return arr[arr.length - 1].length //arr[3].length => 'joyboy'.length =>6
Code 2:
var lengthOfLastWord = function(s) { if (s.length === 0) return 0 let arr = s.trim().split(' ') for (let i = arr.length - 1; i >= 0; i--) { if (arr[i].length > 0) { return arr[i].length } } };