두 영어 단어가 철자의 순서를 뒤바꾸어 같아질 수 있을 때,
그러한 두 단어를 서로 애너그램 관계에 있다고 한다.
예를 들면 occurs 라는 영어 단어와 succor 는 서로 애너그램 관계에 있는데,
occurs의 각 문자들의 순서를 잘 바꾸면 succor이 되기 때문이다.
한 편, dared와 bread는 서로 애너그램 관계에 있지 않다.
하지만 dared에서 맨 앞의 d를 제거하고, bread에서 제일 앞의 b를 제거하면,
ared와 read라는 서로 애너그램 관계에 있는 단어가 남게 된다.
두 개의 영어 단어가 주어졌을 때,
두 단어가 서로 애너그램 관계에 있도록 만들기 위해서 제거해야 하는 최소 개수의 문자 수를 구하는 프로그램을 작성하시오.
문자를 제거할 때에는 아무 위치에 있는 문자든지 제거할 수 있다.
https://www.acmicpc.net/problem/1919
import java.io.*;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String word1 = bf.readLine();
String word2 = bf.readLine();
String[] parts1 = word1.split("");
String[] parts2 = word2.split("");
Arrays.sort(parts1);
Arrays.sort(parts2);
int count1 = 0;
int count2 = 0;
for(int i=0;i<parts1.length;i++){
for(int j=0;j<parts2.length;j++){
if(Objects.equals(parts1[i], parts2[j])){
parts1[i]="0";
parts2[j]="0";
count1++;
count2++;
break;
}
}
}
int result = parts1.length-count1 + parts2.length-count2;
bw.write(result+"");
bw.flush();
bw.close();
}
}
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
int[] countA = new int[26];
int[] countB = new int[26];
for(int i=0;i<a.length();i++){
countA[a.charAt(i)-'a']++; // char - char 계산은 아스키코드로 변환 후 정수 계산 방식으로 전환된다.
}
for(int i=0;i<b.length();i++){
countB[b.charAt(i)-'a']++;
}
int answer = 0;
for(int i=0;i<26;i++){
if(countA[i]>countB[i]){ // A의 단어 갯수가 더 많은 경우
answer += countA[i]-countB[i]; // 만약 a,b 둘다 가지고 있는 단어지만 A가 더 많을 경우 A에서 지워야 할 갯수를 알려준다.
}
if(countB[i]>countA[i]){
answer += countB[i]-countA[i];
}
}
System.out.println(answer+"");
}
}
아스키 코드를 이용한 방법이다.
char-char
를 통해 정수 방식으로 계산하여 몇 번째 인덱스인지 확인하는 방법이다.