贴原题:
leetcode中国:58. 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.
解析:
本题是要计算一个字符串中最后一个单词的长度,每隔一个空格即算一个单词。
那么简单地想,我只要从字符串的最后一个字符开始往前扫描,扫描到空格即跳出,否则计数器加一即可。
但是我们必须考虑这个字符串的最后几位是空格怎么办的问题,以及这是个空字符串等。我第一次提交的时候便没有考虑到字符串最后几位是空格的情况导致出错。引以为戒。下面代码中第二个if中与上n即解决了这个问题。
C代码:
int lengthOfLastWord(char* s) {
int cnt = 0;//计数器,记录最后一个单词的长度
for(int i = strlen(s)-1; i >= 0; i--)//从后向前查找
{
if(*(s+i) != ' ') cnt++;//不是空格则计数
else if(cnt) break;//检测到空格即跳出
}
return cnt;
}