Coding Test/programmers
[프로그래머스] 문자열 내 마음대로 정렬하기 c++
owls
2023. 1. 26. 00:34
728x90
문제 설명
문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다. 예를 들어 strings가 ["sun", "bed", "car"]이고 n이 1이면 각 단어의 인덱스 1의 문자 "u", "e", "a"로 strings를 정렬합니다.
제한 사항
- strings는 길이 1 이상, 50이하인 배열입니다.
- strings의 원소는 소문자 알파벳으로 이루어져 있습니다.
- strings의 원소는 길이 1 이상, 100이하인 문자열입니다.
- 모든 strings의 원소의 길이는 n보다 큽니다.
- 인덱스 1의 문자가 같은 문자열이 여럿 일 경우, 사전순으로 앞선 문자열이 앞쪽에 위치합니다.
입출력 예
strings | n | return |
["sun", "bed", "car"] | 1 | ["car", "bed", "sun"] |
["abce", "abcd", "cdx"] | 2 | ["abcd", "abce", "cdx"] |
풀이
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int index = 0;
bool cmp(string a, string b){
if(a[index] == b[index]){
int len = a.size() < b.size() ? a.size() : b.size();
for(int i = 0; i < len; i++){
if(a[i] == b[i]){
continue;
}
return a[i] < b[i];
}
}
return a[index] < b[index];
}
vector<string> solution(vector<string> strings, int n) {
index = n;
sort(strings.begin(), strings.end(), cmp);
return strings;
}
다른 풀이
string 클래스에 operator<가 없어서 안될거라 생각했는데 있었나봅니다. string 을 비교하기 쉬워졌네요~
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int index = 0;
bool cmp(string a, string b){
return a[index] == b[index] ? a < b : a[index] < b[index];
}
vector<string> solution(vector<string> strings, int n) {
index = n;
sort(strings.begin(), strings.end(), cmp);
return strings;
}
728x90