【LeetCode】53. Length of Last Word

题目描述(Easy)

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.

题目链接

https://leetcode.com/problems/length-of-last-word/description/

Example 1:

Input: "Hello World"
Output: 5

算法分析

从后往前,跳过space后,开始计算长度,直到遇到下一个space

提交代码:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int i = s.size() - 1, len = 0;
        
        while(i >= 0 && s[i] == ' ')
            --i;
        while(i >= 0 && s[i] != ' ')
            --i, ++len;
        
        return len;
    }
};

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82502041
今日推荐