Intuition
find the last index of space
Approach
slice the string from the last index of space than return the length of the string
Complexity
Time complexity: O(n)
Space complexity: O(n)
Code
java
class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
int lastIndex = s.lastIndexOf(" ");
return s.substring(lastIndex+1).length();
}
}
javaScript
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
s = s.trim();
let lastIndex = s.lastIndexOf(" ");
s = s.slice(lastIndex+1);
return s.length;
};
Comments
Post a Comment