Nuggets team number online, help you Offer rimmon! Click to see details

I. Topic Description:

You are given a string s made up of words separated by Spaces. Returns the length of the last word in the string. If the last word does not exist, return 0.

A word is the largest substring that consists of only letters and does not contain any space characters.

 

Example 1: Input: s = "Hello World" Output: 5 Example 2: input: s = "" Output: 0 Prompt: 1 <= s.length <= 104 s Only consists of letters and SpacesCopy the code

Ii. Thinking analysis:

  • If there is a space at the end of the string, remove the space at the end of the string first,
  • And then the string is separated by Spaces,

Three, AC code

/** * @param {string} s * @return {number} */ var lengthOfLastWord = function(s) { const arr = s.trimEnd().split(' '); return arr[arr.length-1].length; }; Execution time: 76 ms Memory: 37.8 MBCopy the code

Four,

  • There’s more than one way, of course,
Var lengthOfLastWord = function(s) {return s.rim ().split(" ").pop().length}; var lengthOfLastWord = function(s) { return s.trim().split(' ').reverse()[0].length };Copy the code

For reference only

Refer to the topic

  • Force button (LeetCode)