본문 바로가기
알고리즘/백준 BOJ

[ BOJ/C# ] 1181 단어 정렬

by 왹져박사 2023. 9. 28.
728x90

https://www.acmicpc.net/problem/1181

 

1181번: 단어 정렬

첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

www.acmicpc.net

말 그대로 조건을 이용하여 풀었다. 

0. 중복된 단어는 하나만 남기고 제거 (먼저 제거해 주는 편이 속도가 빠를 듯하여 먼저 해주었다)

1. 길이가 짧은 것부터

2. 길이가 같으면 사전 순으로

LINQ를 이용하여 풀면 직관적이고 편하지만, 속도 면에서 좋지는 않은 듯 하다. 

2등분이 푸신 코드를 보니 굉장히 직관적이면서도 속도와 메모리를 효율적으로 사용한다. 

using System;
using System.Linq.Expressions;
using System.Text;

namespace B1181
{
    class Program
    {
        static void Main()
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
            StringBuilder sb = new StringBuilder();

            int n = int.Parse(sr.ReadLine());
            List<string> list = new List<string>();
            string[] words = new string[n];
            for(int i = 0; i < n; i++) list.Add(sr.ReadLine());
            list = list.Distinct().ToList();
            words = list.OrderBy(x => x.Length).ThenBy(x => x).ToArray();
            for (int i = 0; i < words.Length; i++) sb.Append(words[i] + "\n");
            sw.Write(sb);
            sr.Close();
            sw.Flush();
            sw.Close();
        }
    }
}

728x90

'알고리즘 > 백준 BOJ' 카테고리의 다른 글

[ BOJ/C# ] 11650 좌표 정렬하기  (0) 2023.09.29
[ BOJ/C# ] 10814 나이순 정렬  (0) 2023.09.29
[ BOJ/C# ] 1260 DFS와 BFS  (0) 2023.09.26
[ BOJ/C# ] 11724 연결 요소의 개수  (0) 2023.09.26
[ BOJ/C# ] 2606 바이러스  (0) 2023.09.24