LeetCode-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.
Example:
1 2
| Input: "Hello World" Output: 5
|
分析
由题目知道,这是求最后一个单词长度的问题 ,但是要考虑的为题是最后一个单词后面可能有无数的空格,因此如果只用空格判断单词之间间隔的话,会造成,最后一个单词不好进行判断。
正确思路
- 判断最后一个是不是空格,如果是空格,直接遍历前面一个,直到找到最后一个单词位置。
- 对每个此时的单词进行技术,我这里因为只用了做下标的i计数,显得略带繁琐
C语言代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| #include "stdio.h" int lengthOfLastWord(char* s) { int sSize = 0; for (sSize = 0; s[sSize] != '\0'; sSize++); int i = sSize - 1;
int space = 0; int flag = 0; for (; i >= 0; i--) {
if(s[i]!=' ') { flag = 1; } if (s[i] == ' ' && flag == 0) {
space++; continue; } else { if (s[i] == ' ') { break; } }
} return sSize-1-space-i; } int main() { char s[]="man is "; printf("%d\n",lengthOfLastWord(s)); return 0; }
|