본문 바로가기

problem solving

[프로그래머스]문자열 내 마음대로 정렬하기

간단하게 버블소트로 구현했다.

좀 더 간단하게 하려면 반복문 안의 else if를 지우고 반복문 순회하기 전에 sort를 사용하면 된다.

반복문을 사용하지 않으면서 더 간결하게 하려면 sort에 compare를 조정해서 사용하는  방법도 있다.

#include <string>
#include <vector>
// #include <algorithm>
 
using namespace std;
 
void swap(string *a, string *b) {
    string temp = *a;
    *= *b;
    *= temp;
}
 
vector<string> solution(vector<string> strings, int n) {
    vector<string> answer;
    
    // sort(strings.begin(), strings.end());
    for(int i = 0; i < strings.size(); i++) {
        for(int j = i + 1; j < strings.size(); j++) {
            if(strings[i][n] > strings[j][n]) {
                swap(strings[i], strings[j]);
            }
            else if(strings[i][n]  == strings[j][n] ) {
                if(strings[i] >  strings[j]) {
                    swap(strings[i], strings[j]);
                }
                 
            }
        }
    }
    
    for(int i = 0; i < strings.size(); i++) {
        answer.push_back(strings[i]);
    }
    return answer;
}
cs

'problem solving' 카테고리의 다른 글

[프로그래머스]실패율  (0) 2020.03.06
[프로그래머스][1차] 비밀지도  (0) 2020.03.06
[프로그래머스]2016년  (0) 2020.03.06
[프로그래머스]체육복  (0) 2020.03.06
[프로그래머스]K번째수  (0) 2020.03.06