LeetCode: Length of Last Word

初始length的时候忘给了0了,2次过

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(const char *s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int beg = 0;
 7         int length = 0;
 8         while (*(s+beg) != '\0') {
 9             if (*(s+beg) == ' ') beg++;
10             else {
11                 length = 0;
12                 while (*(s+beg+length) != '\0') {
13                     if (*(s+beg+length) >= 'a' && *(s+beg+length) <= 'z' || *(s+beg+length) >= 'A' && *(s+beg+length) <= 'Z')
14                         length++;
15                     else break;
16                 }
17                 beg += length;
18             }
19         }
20         return length;
21     }
22 };

 后来写了个更加精简的代码

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(const char *s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         string S;
 7         while (*s != '\0') S += *(s++);
 8         while (S.size() && S[S.size()-1] == ' ') S.erase(S.size()-1, 1);
 9         if (S.rfind(' ') == string::npos) return S.size();
10         else return S.size() - S.rfind(' ') - 1;
11     }
12 };

 C#

1 public class Solution {
2     public int LengthOfLastWord(string s) {
3         int lastAlpha = s.Length - 1;
4         for (; lastAlpha >= 0; lastAlpha--) {
5             if (s[lastAlpha] != ' ') break;
6         }
7         return lastAlpha == -1? 0 : lastAlpha - s.LastIndexOf(' ', lastAlpha);
8     }
9 }
View Code
原文地址:https://www.cnblogs.com/yingzhongwen/p/2995576.html