ddongstudy
단어 정렬 본문
문제
알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
-
길이가 짧은 것부터
-
길이가 같으면 사전 순으로
입력
첫째 줄에 단어의 개수 N이 주어진다. (1≤N≤20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
예제 입력 및 출력
입력
13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours
출력
i
im
it
no
but
more
wait
wont
yours
cannot
hesitate
소스 코드
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;
int N;
bool comp(string a, string b) {
return (a.length() != b.length()) ? (a.length() < b.length()) : (a < b);
}
int main(void) {
cin >> N;
string* arr = new string[N];
for (int i = 0; i < N; i++)
cin >> arr[i];
sort(arr, arr + N, comp);
for (int i = 0; i < N; i++) {
if (i == N - 1 || arr[i].compare(arr[i + 1]) != 0)
cout << arr[i] << endl;
}
}
문제 풀이
-
sort() 함수를 사용하며 사용자 정의 함수를 통해 쉽게 구현할 수 있다.
-
bool comp(strina a, stringb){ }
-
문자열 a와 b를 비교했을 때 길이가 다르면 길이가 긴 문자열이 뒤에 온다.
-
길이가 같으면 맞춤법 순서에 따라 정렬한다.
-