ice rabbit programming

[LeetCode] 58. Length of Last Word 본문

PS/LeetCode

[LeetCode] 58. Length of Last Word

판교토끼 2024. 3. 7. 21:34

https://leetcode.com/problems/length-of-last-word

문제 구성은 매우 쉽게 이해할 수 있다. 띄어쓰기를 구분으로 주어지는 문장에서, 마지막 단어의 길이를 반환하면 된다. 금방 풀 수 있고, 연속해서 공백이 나오거나 앞뒤에 공백이 주어지는 점만 주의하면 된다.

본인은 공백을 기준으로 자르고, 마지막이 공백인 경우를 제외할 수 있도록 처리하였다.

근래에 계속 Python을 이용해서 풀다가, 요즘에는 현업에서 C++을 사용하고 있기에 C++로 풀어보았다.

class Solution {
public:
    int lengthOfLastWord(string s) {
        std::istringstream iss(s);

        std::vector<std::string> tokens;

        std::string token;
        std::string old_token;
        while (std::getline(iss, token, ' ')) {
            if (token.empty()) {
                continue;
            }
            old_token = token;
        }


        return old_token.size();
    }
};

'PS > LeetCode' 카테고리의 다른 글

[LeetCode] 112. Path Sum  (0) 2024.03.07
[LeedCode] 268. Missing Number  (0) 2023.12.27
[LeetCode] 258. Add Digits  (0) 2022.11.10
[LeetCode] 225. Implement Stack using Queues  (0) 2022.11.10
[LeetCode] 232. Implement Queue Using Stacks  (0) 2022.11.10