58. Length of Last Word

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int lengthOfLastWord(string s) 
12     {
13         int len=s.length();
14         if(len==0)
15             return 0;
16         int i=len-1;
17         while(!isalpha(s[i]))
18             --i;
19         if(i<0)
20             return 0;
21         int count=0;
22         while(i>=0)
23         {
24             if(!isalpha(s[i]))
25                 break;
26             ++count;
27             --i;
28         }
29         return count;
30     }
31 };

从后向前扫描,直到第一个字母,开始计数,遇到非字母或者到了字符串头,停止计数,输出结果。

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/8856380.html