This is the 21st day of my participation in the First Challenge 2022

Topic describes

Leetcode address

Find the last word in the string and return the length of the word.

Add: strings are composed of English letters and Spaces.

Here’s an example:

String: 'ABC aaaa' returns:4String: 'ab aaa' returns:3String: 'aaaaaa b c DDDDD' Returns:5
Copy the code

Thought analysis

The first way

Since strings are separated by Spaces, we can use the string split method, split it into an array in the ‘ ‘format, and then reverse the array using the reverse method.

Call the array’s find method, find that the first element is not equal to the empty string, that this is the last word, and return its length.

/ * * *@param {string} s
 * @return {number}* /
var lengthOfLastWord = function (s) {
  var arr = s.split(' ').reverse()
  return arr.find(item= >item ! = =' ').length
};
Copy the code

The second way

The first way is to turn it into an array, and then call the array method, which is a little bit convoluted.

The second way is to use regular expressions that match the end of the string, perhaps with a space at the end, and the word at the end. So, the regular expression can be written as /(\w+)\s*$/, fetching $1, assigning $1 to the previously declared variable, and finally returning its length.

/ * * *@param {string} s
 * @return {number}* /
var lengthOfLastWord = function (s) {
  let str = ' '
  s.replace(/(\w+)\s*$/.($0, $1) = > {
    str = $1
  })
  return str.length
};
Copy the code

The third way

This method iterates through the array from the back using a while loop, finding the first element that is not “, and recording the current index I.

We then continue through the while loop and declare a variable j that records the length of the last word.

In the while loop, we then need to satisfy that I is greater than or equal to j (otherwise we’ll have an infinite loop), and then we need to find the index of the next element equal to”

If you can’t find it, you just keep adding one.

Find it and exit the while loop.

And then the j is the length of the last word.

var lengthOfLastWord = function (s) {
  var i = s.length - 1
  while (s[i] === ' ') {
    i--
  }
  var j = 0
  while(i >= j && s[i - j] ! = =' ') {
    j++
  }
  return j
};
Copy the code