leetcode 1859. Sorting the Sentence

gyubong park·2022년 5월 16일
0

https://leetcode.com/problems/sorting-the-sentence/

문제설명

  • 어절+숫자+띄어쓰기, 하나의 문장을 줌
  • 그런데 이 문장의 순서는 뒤죽박죽, 위 숫자 순서대로 정렬하는 것이 정답

  • "sentence4 a3 is2 This1"
  • 1 -> 2 -> 3 -> 4 순으로 넣어줌
  • "This is a sentence"

문제접근

  • 우선 ' ' 기준으로 하나씩 어절을 분리
  • 뒤에 숫자만큼 array에 기입 (9까지 밖에 없음)
  • 이 array를 하나의 string으로 만들어줌
#include <iostream>
using namespace std;

class Solution {
public:
    string sortSentence(string s) {
        string rtn;
        string str_list[10];

        string part;
        // 띄어쓰기별로 끊음
        // 젤 뒷자리 숫자를 배열에 집어넣음
        while(s.size() > 0){
            int end = s.find(' ');

            if(end > 0){
                part = s.substr(0, end);
                s = s.substr(end+1);
            }else{
                part = s;
                s = "";
            }

            int part_size = part.size();
            int num = part.at(part_size-1)-'0';
            str_list[num] = part.substr(0, part_size-1);

        }

        // 배열을 하나의 string으로 만듬
        for(auto& word : str_list){
            if(!word.empty()){
                rtn += word + " ";
            }
        }

        int size = rtn.size();
        rtn = rtn.substr(0, size-1);

        return rtn;
    }
};

int main() {
    Solution sol;

    // Input: s = "is2 sentence4 This1 a3"
    // Output: "This is a sentence"

    //string s = "is2 sentence4 This1 a3";
    string s = "QcGZ4 TFJStgu3 HvsRImLBfHd8 PaGqsPNo9 mZwxlrYzanuVOUZoyNjt1 fzhdtYIen6 mV7 LKuaOtefsixxo5 pwdEK2";
    auto ans = sol.sortSentence(s);
    cout << ans << endl;

    return 0;
}
profile
초보 개발자

0개의 댓글