Last updated on July 13, 2024
Approach – Regex
This one was pretty straight forward though I fell right within the average performance. Time Complexity O(N).
Here is my solution, it could be optimized though this was my accepted solution with good enough performance:
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function (s) {
let word = s
.replace(/^\s+|\s+$/g, "")
.split(" ")
.pop();
return word.length;
};