第十三周OJ-Q58解题方法

来源:互联网 发布:淘宝怎么设置好友来访 编辑:程序博客网 时间:2024/05/16 08:39
问题:

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.


这个要求最后一个单词的长度,那我们可以从后找起,跳过所有的空格,找到这个句子真正的尾巴。当然,这一点是被这个奇葩的测试用例 a(空格)恶心到了才想到的。然后往前扫,直到碰到另一个空格。其间每走一步用个变量自增一下。比较简单,直接放代码:


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.