반응형
문제
- 문제 링크: 문자열 내 마음대로 정렬하기
코드
(C언어)
solution 1)
더보기
solution 1
#include<>
solution 2)
더보기
#include<>
solution 3)
더보기
#include<>
(C++)
solution 1)
- N: strings의 길이
- S: strings의 문자열의 길이
- 각 문자열을 비교하면서 정렬하므로 시간 복잡도는 O(N*S*logN)
더보기
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int idx;
// 비교 함수
bool compare(string a, string b) {
return a[idx] == b[idx] ? a < b : a[idx] < b[idx];
}
vector<string> solution(vector<string> strings, int n) {
idx = n;
// 각 문자열의 idx번째 문자를 기준으로 정렬
sort(strings.begin(), strings.end(), compare);
return strings;
}
solution 2)
더보기
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int i = 0;
bool str_sort(string a, string b)
{
if (a[i] == b[i])
return a < b;
else
return a[i] < b[i];
}
vector<string> solution(vector<string> strings, int n) {
vector<string> answer;
answer = strings;
i = n;
sort(answer.begin(), answer.end(), str_sort);
return answer;
}
solution 3)
더보기
#include<>
(C#)
solution 1)
더보기
#include<>
solution 2)
더보기
#include<>
solution 3)
더보기
#include<>
(Java)
solution 1)
- N: strings의 길이
- Arrays.sort(): O(NlogN)
- 총 시간 복잡도: O(NlogN)
더보기
import java.util.Arrays;
class Solution {
public String[] solution(String[] strings, int n) {
Arrays.sort(strings, (o1, o2) -> o1.charAt(n) == o2.charAt(n) ?
o1.compareTo(o2) : Character.compare(o1.charAt(n), o2.charAt(n)));
return strings;
}
}
solution 2)
더보기
#include<>
solution 3)
더보기
#include<>
(Python)
solution 1)
- N: strings의 길이
- sorted(): O(NlogN)
- 최종 시간 복잡도: O(NlogN)
더보기
def solution(strings, n):
return sorted(strings, key=lambda x: (x[n], x))
solution 2)
더보기
def solution(strings, n):
answer = []
answer = sorted(strings, key=lambda x: (x[n], x))
return answer
solution 3)
더보기
import
(JavaScript)
solution 1)
- N: strings의 길이
- sort(): O(NlogN)
더보기
function solution(string, n) {
return string.sort(function (a, b) {
if (a[n] === b[n]) {
return a > b ? 1 : -1;
} else {
return a[n] > b[n] ? 1 : -1;
}
});
}
solution 2)
더보기
import
solution 3)
더보기
import
반응형
'1-3. 코딩테스트(프로그래머스) > PCCP(Lv1)' 카테고리의 다른 글
[PCCP] Lv1: K번째 수(42748) 해설 (1) | 2024.12.25 |
---|---|
[PCCP] Lv1: 정수 내림차순으로 배치하기(12933) 해설 (0) | 2024.12.25 |
[PCCP] Lv1: 폰켓몬(1845) 해설 (0) | 2024.12.24 |
[PCCP] Lv1: 신고 결과 받기(92334) 해설 (0) | 2024.12.24 |
[PCCP] Lv1: 완주하지 못한 선수(42576) 해설 (0) | 2024.12.24 |