-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathIsAnagram.java
55 lines (43 loc) · 1.52 KB
/
IsAnagram.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package algorithm.basic;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class IsAnagram {
/*
TASK
주어진 문자열이 애너그램인지를 판단한다.
*/
// 방법 1. O(nlogn) : 정렬 후에 비교하기
// 방법 2. O(n) : 문자열 개수를 세서 비교하기
@Test
public void test() {
assertThat(애너그램판별_USE_MAP("arc", "car"), is(true));
assertThat(애너그램판별_USE_MAP("caaabbb", "abababc"), is(true));
assertThat(애너그램판별_USE_MAP("caabbbb", "abababc"), is(false));
assertThat(애너그램판별_USE_MAP("arc", "carr"), is(false));
assertThat(애너그램판별_USE_MAP("arc", "caz"), is(false));
}
private boolean 애너그램판별_USE_MAP(String str1, String str2) {
if (str1.length() != str2.length()) return false;
Map<Character, Integer> strMap = new HashMap<>();
for (char c : str1.toCharArray()) {
if (strMap.containsKey(c)) {
strMap.put(c, strMap.get(c) + 1);
} else {
strMap.put(c, 1);
}
}
for (char c : str2.toCharArray()) {
if (!strMap.containsKey(c)) {
return false;
}
if (strMap.get(c) == 0) {
return false;
}
strMap.put(c, strMap.get(c) - 1);
}
return true;
}
}