Skip to content

Commit 6541080

Browse files
committed
valid anagram
1 parent 51847b2 commit 6541080

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

โ€Žvalid-anagram/se6816.javaโ€Ž

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/**
2+
ํ’€์ด :
3+
Map์„ ์ด์šฉํ•˜์—ฌ ๋‘ ๋ฌธ์ž์—ด์˜ ๋ฌธ์ž๋“ค์˜ ํšŸ์ˆ˜๋ฅผ ์ €์žฅํ•˜๊ณ  ๋น„๊ตํ•˜๋Š” ๊ฒƒ
4+
5+
๋ณต์žก๋„ ๊ณ„์‚ฐ :
6+
๋ฌธ์ž์˜ ๊ธธ์ด -> N
7+
์‹œ๊ฐ„ ๋ณต์žก๋„ : O(N)
8+
๊ณต๊ฐ„ ๋ณต์žก๋„ : O(N)
9+
*/
10+
class Solution1 {
11+
public boolean isAnagram(String s, String t) {
12+
Map<Character, Integer> targetMap = new HashMap<>();
13+
Map<Character, Integer> diffMap = new HashMap<>();
14+
calculate(s, targetMap);
15+
calculate(t, diffMap);
16+
if(isSameMap(targetMap, diffMap)) {
17+
return true;
18+
} else {
19+
return false;
20+
}
21+
}
22+
23+
public void calculate(String s, Map<Character, Integer> map) {
24+
for(int i = 0; i < s.length(); i++) {
25+
char ch = s.charAt(i);
26+
map.put(ch, map.getOrDefault(ch, 0) + 1);
27+
}
28+
}
29+
30+
public boolean isSameMap(Map<Character, Integer> map, Map<Character, Integer> targetMap) {
31+
if(map.size() != targetMap.size()) {
32+
return false;
33+
}
34+
35+
for(Character key : map.keySet()) {
36+
if(!map.get(key).equals(targetMap.get(key))) {
37+
return false;
38+
}
39+
}
40+
41+
return true;
42+
}
43+
44+
}
45+
/**
46+
ํ’€์ด :
47+
์•ŒํŒŒ๋ฒณ ๋ฌธ์ž ํšŸ์ˆ˜๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ , ๋‘ ๋ฌธ์ž์—ด์˜ ๋ฌธ์ž๋ฅด ์ˆœํšŒํ•˜๋ฉด์„œ ํ•ฉ์„ ๊ตฌํ•จ.
48+
49+
๋ณต์žก๋„ ๊ณ„์‚ฐ :
50+
๋ฌธ์ž์˜ ๊ธธ์ด -> N
51+
์‹œ๊ฐ„ ๋ณต์žก๋„ : O(N)
52+
๊ณต๊ฐ„ ๋ณต์žก๋„ : O(1)
53+
*/
54+
55+
class Solution2 {
56+
public boolean isAnagram(String s, String t) {
57+
58+
if(s.length() != t.length()) {
59+
return false;
60+
}
61+
62+
int[] alphbet = new int[26];
63+
64+
for(int i = 0; i< s.length(); i++) {
65+
int idx = s.charAt(i) - 'a';
66+
alphbet[s.charAt(i) - 'a']++;
67+
68+
int idx2 = t.charAt(i) - 'a';
69+
alphbet[idx2]--;
70+
}
71+
72+
for(int i = 0; i < 26; i++) {
73+
if(alphbet[i] != 0) {
74+
return false;
75+
}
76+
}
77+
78+
return true;
79+
}
80+
81+
}

0 commit comments

Comments
ย (0)