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.

For example, Given s = "Hello World", return 5.

此处要注意的是空格不算单词,也就是说 "abc     ",要返回3

这里需要记住前一个单词的长度
class Solution {
public:
    int lengthOfLastWord(string s) {
        //前一个单词的长度
        int prevWordLen = 0;
        int curWordLen = 0;
        for(int i = 0; i < s.size(); i++){
            if(isalpha(s[i])){
                curWordLen++;

            }
            //避免多个空格的出现,导致结果为0;
            else if(curWordLen != 0){
                prevWordLen = curWordLen;
                curWordLen = 0;
            }
        }
        return curWordLen == 0? prevWordLen: curWordLen;
    }
};

results matching ""

    No results matching ""