문제링크 : https://www.acmicpc.net/problem/1181
문제풀이 : 입력받은 데이터를 sort()함수로 정렬한다.
1. 길이비교 2. 길이가 같은 경우는 사전순대로 정렬해야 하므로 비교 함수를 따로 정의하여 같이 넘겨준다.
소스코드(C++)
/*
* 백준 1181번: 단어 정렬
*/
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool compare(string a, string b) {
if (a.length() == b.length())
return a < b;
else
return a.length() < b.length();
}
int main() {
int N;
cin >> N;
string* arr = new string[N];
for (int i = 0; i < N; i++) {
cin >> arr[i];
}
sort(arr, arr + N, compare);
cout << arr[0] << endl;
for (int i = 1; i < N; i++) {
if (arr[i - 1].compare(arr[i]) == 0) continue;
cout << arr[i] << endl;
}
}
소스코드(Java)
import java.io.*;
import java.util.*;
public class p_1181 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Set<String> set = new TreeSet<String>(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// TODO Auto-generated method stub
// 길이가 같은 경우
if (s1.length() == s2.length()) {
return s1.compareTo(s2);
}
// 길이 비교
else {
if (s1.length() < s2.length()) return -1;
else return 1;
}
}
});
for (int i = 0; i < N; i++) {
set.add(br.readLine());
}
Iterator<String> itr = set.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
// String[] arr = new String[N];
// for (int i = 0; i < N; i++) {
// arr[i] = br.readLine();
// }
//
// Arrays.sort(arr, new Comparator<>() {
// @Override
// public int compare(String s1, String s2) {
// // TODO Auto-generated method stub
// // 길이가 같은 경우
// if (s1.length() == s2.length()) {
// return s1.compareTo(s2);
// }
// // 길이 비교
// else {
// if (s1.length() < s2.length()) return -1;
// else return 1;
// }
// }
// });
//
// // 중복 제거
// for (int i = 0; i < arr.length - 1; i++) {
// if (arr[i].equals(arr[i + 1])) continue;
//
// System.out.println(arr[i]);
// }
//
// // 마지막 값 출력
// System.out.println(arr[N - 1]);
}
}
'Algorithm > 문제풀이' 카테고리의 다른 글
| [백준] 9095번: 1, 2, 3 더하기 (0) | 2019.06.11 |
|---|---|
| [백준] 1463번: 1로 만들기 (0) | 2019.06.11 |
| [백준] 1427번: 소트인사이드 (0) | 2019.06.09 |
| [백준] 2108번: 통계학 (0) | 2019.06.09 |
| [백준] 10989번: 수 정렬하기3 (0) | 2019.06.08 |