문자열 잘라서 정렬하기

Subin·2024년 8월 27일

Algorithm

목록 보기
24/69

[내 풀이]

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<string> solution(string myString) {
    vector<string> answer;
    string str;
    for(char c : myString)
    {
        if(c=='x')
        {
            if(!str.empty())
                answer.push_back(str);
            str="";
        }else
            str+=c;
    }
    if(!str.empty())
        answer.push_back(str);
    sort(answer.begin(), answer.end());
    return answer;
}

[다른 사람 풀이]

#include <string>
#include <vector>
#include <algorithm>
#include <sstream>

using namespace std;

vector<string> solution(string myString) {
    vector<string> answer;

    for(auto& c : myString)
    {
        if( c == 'x')
        {
            c = ' ';
        }
    }

    string str;
    stringstream ss;
    ss.str(myString);
    while(ss >> str)
    {
        answer.emplace_back(str);
    }

    sort(answer.begin(),answer.end());

    return answer;
}

앞 게시물을 참고해서 stringstream을 활용하면,
x자리를 공백으로 둬서 공백으로 단어를 구분해 answer에 넣은 다음 오름차순하는 방법도 있다!

profile
성장하며 꿈꾸는 삶을 살아가고 있는 대학생입니다😊

0개의 댓글