码迷,mamicode.com
首页 > 编程语言 > 详细

(C++練習) 58. Length of Last Word

时间:2019-02-23 01:01:37      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:seq   解法   exist   and   lower   ase   nbsp   cte   code   

題目 :

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.

Example:Input:

  "Hello World"

  Output: 5

大意 : 

找出最後一個字串的長度, 利用space characters 來判斷

解法 : 直接從最後面開始計數字串的長度, 遇到space即回傳長度

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) {
 4         
 5         int len = strlen(s.c_str()) - 1;
 6 
 7         int ans = 0;
 8         for (int i = len; i >= 0; i--){
 9             if (s[i] !=  ) ans++;
10             else if (ans) return ans;
11         }
12 
13         return ans;
14     }
15 };

 

 

(C++練習) 58. Length of Last Word

标签:seq   解法   exist   and   lower   ase   nbsp   cte   code   

原文地址:https://www.cnblogs.com/ollie-lin/p/10421421.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!