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.
利用了isspace来判断‘空格’的位置;
class Solution {
public:
int lengthOfLastWord(string s) {
int n = s.size();
if(n == 0)
return 0;
int lastspace = 0;
int lastalph = 0;
for(int i = 0; i < n; i++){
if(isspace(s[i]))
lastspace = i+1;
else
lastalph = i+1;
}
if(lastspace > lastalph){
lastspace = 0;
n = lastalph;
for(int j = 0; j < (lastalph - 1); j++){
if(isspace(s[j]))
lastspace = j + 1;
}
}
if(lastspace == 0)
return n;
if(lastspace > 0 && lastalph > lastspace)
return n-lastspace;
}
};
本文介绍了一种计算给定字符串中最后一个单词长度的方法。利用isspace函数定位空格位置,以此确定最后一个单词的起始与结束位置。文章通过具体实例进行说明。

被折叠的 条评论
为什么被折叠?



