Home LeetCode - 58. Length of Last Word
Post
Cancel

LeetCode - 58. Length of Last Word

58. 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 (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

제한사항

입출력 예

1
2
Input: "Hello World"
Output: 5

풀이

  • String
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
    int lengthOfLastWord(string s) {
        std::vector<std::string> tokens;
        std::string buf;
        std::stringstream ss(s);
        
        while(ss >> buf) {
            tokens.emplace_back(buf);
        }
        
        if (tokens.empty()) {
            return 0;   
        }
        
        return tokens.back().size();
    }
};
This post is licensed under CC BY 4.0 by the author.