728x90
문자열 내 마음대로 정렬하기
코딩테스트 연습 - 문자열 내 마음대로 정렬하기
문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다. 예를 들어 strings가 [sun, bed, car]이고 n이 1이면 각 단어의 인덱스 1�
programmers.co.kr
문제 설명
내장되어있는 정렬함수를 이용할 줄 아는지 물어보는 문제
문제 풀이
소스코드 : C++
#include<iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int N;
bool comp(string a, string b){
if(a[N]==b[N])return a<b;
else return a[N]<b[N];
}
vector<string> solution(vector<string> strings, int n) {
N=n;
sort(strings.begin(),strings.end(),comp);
return strings;
}
소스코드 : Python
def solution(strings, n):
return sorted([s for s in strings],key = lambda a:[a[n],a])
728x90
300x250