본문 바로가기

Algorithms/Cracking the Coding Interview

Strings: Making Anagrams

Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not.

Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number?

Given two strings,  and , that may or may not be of the same length, determine the minimum number of character deletions required to make  and  anagrams. Any characters can be deleted from either of the strings.

This challenge is also available in the following translations:

Input Format

The first line contains a single string, 
The second line contains a single string, .

Constraints

  • It is guaranteed that  and  consist of lowercase English alphabetic letters (i.e.,  through ).

Output Format

Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.

Sample Input

cde
abc

Sample Output

4

Explanation

We delete the following characters from our two strings to turn them into anagrams of each other:

  1. Remove d and e from cde to get c.
  2. Remove a and b from abc to get c.

We must delete  characters to make both strings anagrams, so we print  on a new line.


풀이


알파벳을 아스키코드로 이용해서 풀이한 방식이다.


먼저 first에서 알파벳 각각의 index에 +1을 추가한다.


뒤이어서 second에서 해당 알파벳의 index에 있는 값을 -1씩 하면 a와 b 둘 다 가지고 있는 공통의 알파벳 index에 해당하는 값이 없어진다.

(test case의 경우 c만 없어지고 de, ab가 남는 상황)


first보다 second에서 더 많이 나온 알파벳 철자가 있는경우 -가 나오기 때문에 절대값으로 더해주는 걸로 마무리

package datastructure;

import java.util.Scanner;

public class MakingAnagrams {
public static int numberNeeded(String first, String second) {
int sum = 0;
int [] alphabet = new int[26];
for (char c : first.toCharArray()){
alphabet[c - 'a']++;
}
for (char c : second.toCharArray()){
alphabet[c - 'a']--;
}
for (int i : alphabet){
sum += Math.abs(i);
}
return sum;
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.next();
String b = in.next();
System.out.println(numberNeeded(a, b));
}
}


'Algorithms > Cracking the Coding Interview' 카테고리의 다른 글

Queues: A Tale of Two Stacks  (0) 2018.02.20
Stacks: Balanced Brackets  (0) 2018.02.19
Linked Lists: Detect a Cycle  (0) 2018.02.19
Hash Tables: Ransom Note  (0) 2018.02.09
Arrays: Left Rotation  (0) 2018.02.08