【字符串】58. 最后一个单词的长度

题目:

解答:

(1)从前向后扫描,找到我们所关注的最后一个word,然后计算其长度。

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) 
 4     {
 5         int ctr = 0;
 6         int last_ctr = 0;
 7 
 8         for (int i = 0; s[i] != '\0'; i++)
 9         {
10             if (s[i] == ' ')
11             {
12                 if (ctr > 0)
13                 {
14                     last_ctr = ctr;
15                 }
16                 ctr = 0;
17             }
18             else
19             {
20                 ctr++;
21             }
22         }
23         if (ctr == 0 && last_ctr > 0) // 最后一个word后面有空格
24         {
25             return last_ctr;
26         }        
27 
28         return ctr;
29     }
30 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12822687.html