Baekjun No. 1181, word alignment (with.Java)
This article explores Baekjoon Problem 1181, Word Sorting (with Java).
We will learn by solving coding test problems, reflecting on previous problems, and exploring different solution methods.
Letβs first look at the problem.
Problem
Write a program that sorts N words consisting of lowercase letters according to the following conditions.
Input
The first line contains the number of words, N.
(1 β€ N β€ 20,000). Starting from the second line, N lines contain words, one per line, each consisting of lowercase letters.
The length of the given string does not exceed 50.
Output
Sort the words according to the given condition and output them.
Problem Solution
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.valueOf(br.readLine());
String[] arr = new String[N];
for(int i = 0; i < N; i++){
arr[i] = br.readLine();
}
for(int i = 0; i < N; i++){
for(int j = i + 1; j < N; j++){
if(arr[i].length() == arr[j].length()){
if(arr[i].compareTo(arr[j]) > 0){
String temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}else{
if(arr[i].length() > arr[j].length()){
String temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
for(int i = 0; i < N; i++){
if(i > 0){
if(arr[i].compareTo(arr[i - 1]) != 0){
System.out.println(arr[i]);
}
}else{
System.out.println(arr[i]);
}
}
}
}
Solution Explanation
This code sorts an array of strings by length and alphabetically, then removes duplicate strings and prints them.
First, it uses a BufferedReader to receive input.
It reads the number of strings N from the first line and stores the N strings in the array arr.
Next, it sorts the array using a double for loop.
There are two criteria for sorting.
First, it sorts the shortest strings first.
Second, if the lengths are the same, they are sorted lexicographically. This process ensures the array is in the desired order.
After sorting is complete, the array is traversed again, removing duplicate strings and outputting them.
The first element of the array is unconditionally output, and subsequent elements are output only if they differ from the previous element.
This process outputs the sorted result with duplicate strings removed.