[Hackerrank] Strings - Anagrams 풀이

예문


https://www.hackerrank.com/challenges/java-anagrams/problem

Sample Input 0

anagram
margana

Sample Output 0

Anagrams

Explanation 0

Character Frequency: anagram Frequency: margana
A or a 3 3
G or g 1 1
N or n 1 1
M or m 1 1
R or r 1 1

The two strings contain all the same letters in the same frequencies, so we print “Anagrams”.

Sample Input 1

anagramm
marganaa

Sample Output 1

Not Anagrams

Explanation 1

Character Frequency: anagramm Frequency: marganaa
A or a 3 4
G or g 1 1
N or n 1 1
M or m 2 1
R or r 1 1

The two strings don’t contain the same number of a’s and m’s, so we print “Not Anagrams”.

Sample Input 2

Hello
hello

Sample Output 2

Anagrams

Explanation 2

Character Frequency: Hello Frequency: hello
E or e 1 1
H or h 1 1
L or l 2 2
O or o 1 1

The two strings contain all the same letters in the same frequencies, so we print “Anagrams”.


해석

  • Anagram : 철자 순서를 바꾸는 것
  • 문자열 a, b 가 Anagram 이 되면 Angrams 출력, 아니면 Not Angrams 출력

풀이

  • LowerCase or UpperCase 로 맞춤
  • 아스키 코드 값을 이용한 배열 저장
  • 배열 값으로 sum 값 계산

제약사항

  • 1 <= length(a), length(b) <= 50
  • 문자열 a,b : 영어 알파벳으로 구성
  • 대소문자 구분하지 않음

코드

static boolean isAnagram(String a, String b) {
  if (a.length() != b.length())
    return false;

  int[] temp = new int[128]; //ascii code length 128
  a = a.toLowerCase();
  b = b.toLowerCase();
  int sum = 0;

  for (int i = 0; i < a.length(); i++) {
    sum += ++temp[a.charAt(i)] <= 0 ? -1 : 1;   // increment
    sum += --temp[b.charAt(i)] >= 0 ? -1 : 1;   // decrement
  }
  return sum == 0;
}