Created
March 5, 2022 09:56
-
-
Save esase/68aa832a580d0fa5591fb1970b607016 to your computer and use it in GitHub Desktop.
Length of last word [https://leetcode.com/problems/length-of-last-word]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s | |
* @return {number} | |
*/ | |
var lengthOfLastWord = function(s) { | |
let maxWordLength = 0; | |
let startCollecting = false; | |
for (let i = s.length - 1; i >= 0; i--) { | |
if (s[i] === ' ' && startCollecting) { | |
return maxWordLength; | |
} | |
if (s[i] !== ' ') { | |
maxWordLength++; | |
startCollecting = true; | |
} | |
} | |
return maxWordLength; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment