Sunday, February 23, 2014

[LEETCODE] Length of Last Word


[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.

A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World",
return 5.

思路:
最后一个单词的2种情况:
1, *hello; 2, *hello* ; *代表空格,可以为一个也可以为多个;
从前向后扫描,遇到空格就计算当前单词的长度,然后移动指针到下一个不是空格的地方继续计算,如果是情况1,指针移动到最后的‘\0’ 时,长度还未计算,所以循环结束之后再计算一次长度。



代码:
int lengthOfLastWord(const char *s) {
int len =0;
const char *start = s;
while( *s !='\0'){
if( *s == ' '){
len = s - start;
while( *s == ' ' ){ s++; }
start = s;
continue;
}
s++;
}
if( *start != '\0')
len = s -  start;
return len;
}

No comments:

Post a Comment