题目
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.
Example:1
2Input: "Hello World"
Output: 5
分析
由题目知道,这是求最后一个单词长度的问题 ,但是要考虑的为题是最后一个单词后面可能有无数的空格,因此如果只用空格判断单词之间间隔的话,会造成,最后一个单词不好进行判断。
正确思路
- 判断最后一个是不是空格,如果是空格,直接遍历前面一个,直到找到最后一个单词位置。
- 对每个此时的单词进行技术,我这里因为只用了做下标的i计数,显得略带繁琐
C语言代码
1 |
|