코테준비 - Length of Last Word

정상화·2023년 2월 26일

LeetCode

목록 보기
56/222

Length of Last Word

class Solution {
public:
    int lengthOfLastWord(string s) {
        int len = 0;
        stack<int> res;
        for (auto it = s.begin(); it != s.end(); it++) {
            if(*it != ' '){
                len++;
            }
            else
            {
                res.push(len);
                len = 0;
            }
        }
        res.push(len);
        while (!res.empty() && res.top() == 0) {
            res.pop();
        }

        return res.empty() ? 0 : res.top();
    }
};
profile
백엔드 희망

0개의 댓글