땀두 블로그

[백준] 1235번 - 학생 번호 본문

알고리즘/백준

[백준] 1235번 - 학생 번호

땀두 2022. 3. 22. 08:02

 

문자열 매칭 문제이다. 문자열의 끝에서부터 유일한 값들을 가지게 할 수 있는 집합을 만들어야 하므로 HashSet을 이용해주었고, 한 번의 탐색이 끝나면 HashSet을 초기화하고, 인덱스와 문자의 길이를 변경해주어서 탐색하였다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;

public class p1235 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		int a = Integer.parseInt(br.readLine());
		String[] ary = new String[a];

		for (int i = 0; i < a; i++) {
			ary[i] = br.readLine();
		}

		HashSet<String> set = new HashSet<>();
		int len = ary[0].length();
		int idx = len - 1;

		for (int i = 1; i < len; i++) {
			int cnt = 0;
			for (int j = 0; j < a; j++) {
				if (!set.contains(ary[j].substring(idx))) {
					set.add(ary[j].substring(idx, idx + i));
					cnt++;
				}
			}
			if (cnt == a) {
				System.out.println(i);
				return;
			} else {
				idx--;
				set.clear();
			}
		}
	}
}
 

 

 

Comments