Leetcode | 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.
这题是要求最后一个单词的长度。而且因为输入是一个char *,而不是已经长度的数组,所以从左往右扫。碰到空格就保留它的位置。碰到非空格就计算长度。如果前面没有空格,就直接和字符串开头相比较。如果有空格就和最近的空格比较。
这种方法就可以忽略末尾是不是有空格,或者连续空格等情况了。
1 class Solution { 2 public: 3 int lengthOfLastWord(const char *s) { 4 const char *p = s, *space = NULL; 5 int l = 0; 6 for (; *p != '\0'; p++) { 7 if (*p == ' ') { 8 space = p; 9 } else if (space == NULL) { 10 l = p - s + 1; 11 } else { 12 l = p - space; 13 } 14 } 15 return l; 16 } 17 };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步