LeeCode from 0 ——58. Length of Last Word

Posted ssml

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeeCode from 0 ——58. Length of Last Word相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeeCode from 0 —— 67. Add Binary

LeeCode from 0 ——38. Count and Say

leecode第一百二十一题(买卖股票的最佳时机II)

leecode第五十八题(最后一个单词的长度)

leecode第三题(无重复字符的最长子串)

Leecode????????????-C??????/python-58.???????????????????????????