1、leetcode问题描述:
Length of Last Word
Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World"
,
return 5
.
2、解题思路:
用JavaScript内置的split()分割字符串s,定义变量len=0。从后往前遍历,若分割后得到的数组的最后一个值不是''(这是为了排除字符串s在最后一个单词后面还带着空格的情况,如s='a '),则该值的字符串长度赋值给len并结束循环,否则继续向前遍历。最后返回len。
3、JavaScript解题代码:
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
var words=s.split(' '),len=0;
for(var i=words.length-1;i>=0;i--){
if(words[i]!==''){
len=words[i].length;
break;
}
}
return len;
};
来源:oschina
链接:https://my.oschina.net/u/1447138/blog/476417