Length of Last Word 题解
题目来源: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.
解题思路:
去掉首位的空格, 从最后往前走到第一个空格或开头停止。
int lengthOfLastWord(const char *s)
{
char * start = const_cast<char*>(s);
while(*start == ' ' && *start != '\0')
start++;
if(*start == '\0') return 0;
char * end = start;
while(*(end+1) != '\0')
end++;
while(*end == ' ') --end;
int len = 0;
while(end >= start && *end !=' ')
++len, --end;
return len;
}这个思路用STL写就简单了, ref。 std::ptr_fun 模版取函数指针.
直接从前往后,记录每一个单词的长度,后面的单词长度会取代前面的长度,注意得跳过中间的连续空格。
Last updated
Was this helpful?