Skip to content

058. Length of Last Word

难度Easy

刷题内容

原题连接

  • https://leetcode.com/problems/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.

思路 **- 时间复杂度: O(n)- 空间复杂度: O(1)***

这题我们只要从字符串的末尾开始向前找到第一个单词即可

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

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组