프로그래머스 - 내 풀이/프로그래머스 Lv1
프로그래머스 / 연습문제 / 문자열 내림차 순으로 배치하기
ENUM01
2020. 5. 1. 10:04
https://programmers.co.kr/learn/courses/30/lessons/12917?language=cp
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#include <string>
#include <vector>
using namespace std;
string solution(string s) {
for (int i = 0; i < s.size(); i++)
{
for (int j = i+1; j < s.size(); j++)
{
if (s[i] < s[j]) //뒤에 있는 문자열이 더 클 경우
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
return s;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
나 같은 경우는 직접 정렬을 구현했지만, 알고리즘 헤더의 greater를 사용하면 다음과 같이
간단하게 풀 수 있다.
algorithm의 sort를 이용해서 내림차순으로 정렬해서 해결 가능
- algorithm의 sort는 기본적으로 오름차순으로 정렬을 시켜준다.
- void sort(T start, T end, Compare comp)
- sort메서드의 3번째 인자를 넣지 않으면 default로 오름차순 정렬
- 3번째 인자에 사용자가 정의한 함수를 기준으로 정렬 가능
vodi(v.begin(),v.end(),greater<자료형>())
functional를 include하면 less,greater,plus,minus를 사용할 수 있다.
greater : 첫 번째 인자가 두 번째 인자보다 크면 true
less : 첫 번째 인자가 두 번째 이낮보다 작으면 true
plus : 두 개의 인자를 더한 값 반환
minus : 첫번째 인자에서 두 번째 인자를 뺀 값 반환
1
2
3
4
5
6
7
8
9
10
11
|
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
string solution(string s) {
sort (s.begin(), s.end(), greater<char>());
return s;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|