https://www.acmicpc.net/problem/5052
처음에는 ArrayList 에 담아서 모두 순회하면서 비교해야하나 고민했다
하지만 좀 더 생각해보니 알파벳 순서대로 정렬되있으면 인접한 것만 비교하면된다는 생각이 들었다
알파벳 순서대로 정렬되도록 TreeSet에 넣고
인접한 것들만 서로 비교하면 된다
String 과 StringBuilder 를 비교할때는
StringBuilder 의 toString 함수를 사용해야 문자를 비교할 수 있다
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
TreeSet<String> tree = new TreeSet<>();
StringBuilder sb = new StringBuilder();
StringBuilder ans = new StringBuilder();
for(int i = 0; i < t; ++i)
{
tree.clear();
int n = Integer.parseInt(br.readLine());
for(int j = 0; j < n; ++j)
{
tree.add(br.readLine());
}
boolean same = false;
for(String el : tree)
{
if(sb.length() != 0)
{
if(sb.length() >= el.length())
{
sb.setLength(el.length());
if(sb.toString().equals(el))
{
same = true;
break;
}
}
else
{
if(sb.toString().equals(el.substring(0, sb.length())))
{
same = true;
break;
}
}
}
sb.setLength(0);
sb.append(el);
}
sb.setLength(0);
if(same == false)
{
ans.append("YES\n");
}
else
{
ans.append("NO\n");
}
}
System.out.println(ans);
}
}
다시 풀어봄 쉽게 풀었다;;
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for (int i = 0; i < t; i++) {
int n = Integer.parseInt(br.readLine());
String[] arrstr = new String[n];
for (int j = 0; j < n; j++) {
arrstr[j] = br.readLine();
}
Arrays.sort(arrstr);
boolean No = false;
for (int j = 0; j < n; j++) {
if((j+1) < n && arrstr[j+1].indexOf(arrstr[j]) == 0){
No = true;
break;
}
}
if(No)
System.out.println("NO");
else
System.out.println("YES");
}
}
}