GitHubSeob
C++ / 프로그래머스 / 문자열 내 마음대로 정렬하기 본문
문제
https://programmers.co.kr/learn/courses/30/lessons/12915
코딩테스트 연습 - 문자열 내 마음대로 정렬하기
문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다. 예를 들어 strings가 ["sun", "bed", "car"]이고 n이 1이면 각 단어의 인덱
programmers.co.kr
문제풀이
algorithm의 sort를 이용하여 정렬을 하면 된다.
따로 compare함수를 만들어서 idx번째 순으로 정렬을 하게 한다, 둘이 같을 경우 사전 순으로 정렬을 한다.
코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int idx;
bool compare(string s1, string s2){
if(s1[idx]<s2[idx])
return true;
else if(s1[idx]==s2[idx])
return s1<s2;
else return false;
}
vector<string> solution(vector<string> strings, int n) {
idx=n;
sort(strings.begin(),strings.end(),compare);
return strings;
}
'Programmers > Level 1' 카테고리의 다른 글
C++ / 프로그래머스 / 문자열 내림차순으로 배치하기 (0) | 2021.09.06 |
---|---|
C++ / 프로그래머스 / 문자열 내 p와 y의 개수 (0) | 2021.09.06 |
C++ / 프로그래머스 / 두 정수 사이의 합 (0) | 2021.09.06 |
C++ / 프로그래머스 / [1차] 다트 게임 (0) | 2021.09.06 |
C++ / 프로그래머스 / [1차] 비밀지도 (0) | 2021.08.30 |