๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Length of Last Word

by dkswnkk 2021. 11. 14.

๋ฌธ์ œ

 

Length of Last Word - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

์ฝ”๋“œ

class Solution {
public:
    int lengthOfLastWord(string s) {

        vector<string>parsing;

        string temp;

        for(int i=0; i<s.length()+1; i++){
            if(s[i]!=' '&&s[i]!='\0') temp+=s[i];
            else{
                parsing.push_back(temp);
                temp.clear();
            }
        }
        reverse(parsing.begin(),parsing.end());

        for(string s:parsing){
            if(s.length()!=0) return s.length();
        }
        return 0;
    }
};

 

ํ’€์ด

๋„์–ด์“ฐ๊ธฐ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ž๋ฅธ ๋‹จ์–ด๋“ค์„ parsing ๋ฒกํ„ฐ์— ๋„ฃ์–ด์ฃผ๊ณ  ๋ฒกํ„ฐ์˜ ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค์˜ ๋ฌธ์ž์—ด์„ ์ถœ๋ ฅํ•˜๋Š”๋ฐ " fly me to the moon   " ์™€ ๊ฐ™์ด ๋งจ ๋’ค๊ฐ€ ๋„์–ด์ง„ ์ฑ„๋กœ ์‹œ์ž‘ํ•˜๋Š” input๊ฐ’์ด ๋“ค์–ด์˜ฌ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ 0 ์ด์ƒ์ธ ๋งจ ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค์˜ ๋ฌธ์ž์—ด์„ ์ถœ๋ ฅํ•˜์—ฌ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค๋‹ˆ๋‹ค.

๋Œ“๊ธ€