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
.
题意:求一字符串中最后一个单词中的长度
分析:
注意几种特殊情况:
1)空字符串,返回0
2)全部都是空格
3)最后几个字符是空格
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
var arrayCount = s.split(" ");
var len = arrayCount.length - 1;
while (arrayCount[len] === "") {
len--;
}
var lastStr = arrayCount[len];
if (lastStr === undefined) {
return 0;
}
return lastStr.length;
};