题目摘要
给定一个字符串, 包含大小写字母、空格' '
,返回最后一个单词长度。若不存在,返回 0 。
解法
1. 用双指针法,从后面开始,先找到最后一个单词的最后一个字母,从该位置开始,找到最后一个单词的第一个字母
2. 令单词长度为0,从最后一个字母开始往前找,如果单词长度为0且字母为空格,则i–,否则长度加一;如果长度不为0,且单词不为空格,则长度加一,否者跳出循环。
注意
原题
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
.