문제
Professor Lew teaches Algorithm course in Sonyusi University (소녀시대학교).
It is his first year as a professor, so he spends a lot of time making lecture notes.
He'll teach recursion and sorting algorithms in the next class,
and he wants to make some examples which will be included in his lecture note.
While making some examples for his lecture note, he noticed that one of his work was quite difficult.
The example was for sorting a string, and the exact process was as follows:
First, the original string of length 2n is divided into n substrings, each of length 2.
Then sort the n strings in lexicographic order, and then concatenate them to obtain the result string.
Note that the sorting process will be performed on n strings, but not each of the n strings.
The following example illustrates the process:
abbaaccb → ab ba ac cb → ab < ac < ba < cb → abacbacb
Since the process was quite confusing,professor Lew decides to use a computer program for verification.
Given an alphabetic string of even length, write a program that prints the result of the sorting process.
출력
For each test case, print the result in one line.
예제 출력
abacbacb
aababbccdcdd
babababybybyeeeeegeggege
oh
package kwo2002.java.lecture;
import java.util.ArrayList;
import java.util.List;
/**
* Created by kwo2002 on 2015-08-19.
*/
public class Main {
public String sortString(String text) {
if (text.length() % 2 == 1) {
throw new IllegalArgumentException();
}
List<String> textList = new ArrayList<>();
for (int i = 0; i < text.length(); i++) {
if (i % 2 == 0) {
textList.add(text.substring(i, i + 2));
}
}
StringBuilder sb = new StringBuilder();
textList.stream().sorted().forEach(s -> sb.append(s));
return sb.toString();
}
public static void main(String[] args) {
Main main = new Main();
System.out.println(main.sortString("abbaaccb"));
}
}
회고.
스칼라로 풀어보려다가 스칼라의 List 사용법을 잘 몰라서 익숙한 자바로 바꿨다.
문자열을 두글자씩 나눈다음, List에 담고 List의 sort 기능을 이용해서 간단히 처리했는데,,
알고리즘에서 원하는건 직접 정렬을 하는건가..? 긁적긁적..