码迷,mamicode.com
首页 > 其他好文 > 详细

LeeCode from 0 ——58. Length of Last Word

时间:2018-06-22 13:18:31      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:str   space   空格   --   判断   rac   cte   def   nsis   

58. 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.

Example:

Input: "Hello World"
Output: 5

解题思路:
1)判断是否以空格结尾,且以末端空格所占位数;
2)从末端非空格位开始,向前循环,非空格位加1,循环到新的空格位则跳出循环。
c++代码如下:
class Solution {
public:
    int lengthOfLastWord(string s) {
        int n=s.length();
        int sum=0;
        int nums=0;
       for(int j=n-1;j>=0;j--){
            if(s[j]==‘ ‘)
             nums++;
             else
                 break;
        }
        for(int i=n-nums-1;i>=0;i--){
            
            if(s[i]!=‘ ‘)
                sum++;
            else
                break;   
        }
        return sum;
        
    }
};

LeeCode from 0 ——58. Length of Last Word

标签:str   space   空格   --   判断   rac   cte   def   nsis   

原文地址:https://www.cnblogs.com/ssml/p/9212578.html

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