Skip to content

Latest commit

 

History

History
executable file
·
37 lines (29 loc) · 866 Bytes

0058._Length_of_Last_Word.md

File metadata and controls

executable file
·
37 lines (29 loc) · 866 Bytes

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

思路 - 时间复杂度: 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;
    }
};