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.

这道题的要求是返回字符串中最后一个单词的长度。

遍历字符串,统计单词长度。只有一点需要注意,就是最后单词后面有空格的情况,因此需要判断下一字符是否是字母,如果是,这重置长度为0即可。

时间复杂度:O(n)

空间复杂度:O(1)

当然,,也可以引入计数器遍历cnt用于记录当前单词长度,只有当cnt加1的时候,更新结果变量res。

你曾经说,等我们老的时候,

58. Length of Last Word

相关文章:

你感兴趣的文章:

标签云: