[백준(Baekjoon)][자바(java)] 7587 : Anagram

728x90

 

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

 

7587번: Anagrams

Output consists of one word from each list, the word with the most anagrams within the list, followed by a space, followed by the number of anagrams. The word displayed will be the first occurrence in the list of the anagram. If more than one word has the

www.acmicpc.net

 

문제 풀이

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {

	public static boolean anagram(String A, String B) {
		if (A.length() != B.length()) return false;
		char[] a = A.toCharArray(), b = B.toCharArray();
		Arrays.sort(a);
		Arrays.sort(b);
		return Arrays.equals(a, b);
	}

	public static boolean anagram2(String A, String B) {
		if (A.length() != B.length()) return false;
		int[] a = new int[26];
		for (char c : A.toCharArray())
			a[c - 'a']++;
		for (char c : B.toCharArray()) {
			a[c - 'a']--;
			if (a[c - 'a'] < 0) return false;
		}
		return true;
	}

	public static void main(String[] args) throws Exception {

		BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
		int n, c, mc, mi, i, j;
		String[] s; boolean[] b; String A, B;
		StringBuilder sb = new StringBuilder();
		while (true) {
			n = Integer.parseInt(br.readLine());
			if (n == 0) break;
			s = new String[n];
			for (i = 0; i < n; ++i)
				s[i] = br.readLine();
			b = new boolean[n];
			mc = mi = -1;
			for (i = 0; i < n - 1; ++i) {
				if (b[i]) continue;
				A = s[i]; c = 0;
				for (j = i + 1; j < n; ++j) {
					if (b[j]) continue;
					B = s[j];
					if (anagram(A, B)) {
						c++;
						b[j] = true;
					}
				}
				if (c > 0) {
					if (mc < c) {
						mc = c; mi = i;
					}
				}
			}
			sb.append(s[mi] + " " + mc + "\n");
		}
		br.close();
		System.out.println(sb.toString());
	}
}

 

 

반응형