https://leetcode.com/problems/length-of-last-word/
var lengthOfLastWord = function (s) {
let str = trim(s);
let word = "";
for (let i = str.length - 1; i >= 0; i--) {
if (str[i] !== ' ') {
word += str[i];
continue;
}
break;
}
return word.length;
};
function trim(str) {
let start = 0;
let end = str.length - 1;
for (let i = 0; i < str.length; i++) {
if (str[i] === ' ') {
++start;
continue
}
break;
}
for (let i = str.length - 1; i >= 0; i--) {
if (str[i] === ' ') {
--end;
continue
}
break;
}
return str.slice(start, end + 1);
}
I made two mistakes during the process I solve this problem
- I forgot to add
continue
inif
condition expression - I wrote
str
ass
.......... I think I need to pay more attention when writing the code
we can solve this problem in one line with some built-in methods
var lengthOfLastWord = function (s) {
return s.trim().split(" ").pop().length;
}
the first method which is too complexity is my thoughts and there is a better method with similar thoughts in discussion board
var lengthOfLastWord = function (s) {
let len = 0;
let hasStarted = false;
for (let i = s.length - 1; i >=0; i--) {
if (s[i] !== " ") hasStarted = true;
if (hasStarted) {
if (s[i] === " ") break;
len++;
}
}
return len;
}