【Leetcode】【Easy】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.

解题思路1:

遍历字符串,设置整形变量n,记录当前遍历到的无空格子串的长度,如果子串后遇到空格,且空格后再次遇到新的子串,则更新n,否则返回n;

注意:

本题容易忽略的是,返回最后一个子串的长度,不能简单想做遇到空格就重新计数,因为可能空格后不再有子串了,也就是最后一个子串结束后,字符串没有完,还有空格存在。因此要注意对这种情况进行判断。

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) {
 4         int len = s.size();
 5         int len_lw = 0;
 6         
 7         for (int i = 0; i < len; ++i) {
 8             if (i != 0 && s[i-1] == ' ' && s[i] != ' ')
 9                 len_lw = 0;
10             if (s[i] != ' ')
11                 len_lw++;
12         }
13         
14         return len_lw;
15     }
16 };

解题思路2:

直接从后遍历字符串,先过滤尾部的空格,之后遍历的第一个子串长度就是要返回的结果。

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(const char *s) {
 4         int len = strlen(s);
 5         int sum = 0;
 6         
 7         while (s[len-1] == ' ') 
 8             len--;
 9             
10         for (int i=len-1; i>=0; i--) {
11             if(s[i]!=' ')   
12                 sum++;
13             else 
14                 break;
15         }
16         
17         return sum;
18     }
19 };

附录:

1、C语言中的char* char const char 和C++ string的关系

2、C++中对字符串操作的函数总结

3、灵活运用字符串指针,多用指针操作,少用数组操作

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(const char* s) {
 4         int len = 0;
 5         
 6         while (*s) {
 7             if (*s++ != ' ')
 8                 ++len;
 9             else if (*s && *s != ' ')
10                 len = 0;
11         }
12         
13         return len;
14     }
15 };
原文地址:https://www.cnblogs.com/huxiao-tee/p/4147688.html