Skip to content

Commit e832a64

Browse files
committed
valid anagram solution
1 parent d87b7ed commit e832a64

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

โ€Žvalid-anagram/Yn3-3xh.javaโ€Ž

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
[๋ฌธ์ œํ’€์ด]
3+
- char ๋ฐฐ์—ด๋กœ ๋งž์ถฐ๋ณด์ž (x)
4+
- s์™€ t์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™์•„์•ผ ํ•œ๋‹ค.
5+
- ๊ฐ ์ฒ ์ž์˜ ๊ฐœ์ˆ˜๊ฐ€ s์™€ t ๋ชจ๋‘ ์ผ์น˜ํ•˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค. (ํ…Œ์ŠคํŠธ์ผ€์ด์Šค ํ•˜๋‚˜ ์‹คํŒจ)
6+
7+
- s ์ฒ ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ์–ด ๋†“๊ณ , t ์ฒ ์ž์˜ ๊ฐœ์ˆ˜๋Š” ํ•˜๋‚˜์”ฉ ๋นผ์„œ 0์„ ์ฒดํฌํ•ด๋ณด์ž. Map (O)
8+
time: O(N), space: O(N)
9+
class Solution {
10+
public boolean isAnagram(String s, String t) {
11+
if (s.length() != t.length()) {
12+
return false;
13+
}
14+
15+
Map<Character, Integer> counting = new HashMap<>();
16+
for (char ch : s.toCharArray()) {
17+
counting.put(ch, counting.getOrDefault(ch, 0) + 1);
18+
}
19+
for (char ch : t.toCharArray()) {
20+
if (!counting.containsKey(ch)) {
21+
return false;
22+
}
23+
counting.put(ch, counting.get(ch) - 1);
24+
}
25+
26+
return counting.values().stream()
27+
.allMatch(count -> count == 0);
28+
}
29+
}
30+
31+
- Arrays๋กœ ์ •๋ ฌ ๋ฐ ๋น„๊ต๋ฅผ ํ•ด๋ณด์ž. (O)
32+
time: O(NlogN), space: O(N)
33+
class Solution {
34+
public boolean isAnagram(String s, String t) {
35+
if (s.length() != t.length()) {
36+
return false;
37+
}
38+
39+
char[] sToCharArray = s.toCharArray();
40+
char[] tToCharArray = t.toCharArray();
41+
Arrays.sort(sToCharArray);
42+
Arrays.sort(tToCharArray);
43+
44+
return Arrays.equals(sToCharArray, tToCharArray);
45+
}
46+
}
47+
48+
- s ์ฒ ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ์–ด ๋†“๊ณ , t ์ฒ ์ž์˜ ๊ฐœ์ˆ˜๋Š” ํ•˜๋‚˜์”ฉ ๋นผ์„œ 0์„ ์ฒดํฌํ•ด๋ณด์ž. Array (O)
49+
time: O(N), space: O(1)
50+
51+
[ํšŒ๊ณ ]
52+
Arrays์ฒ˜๋Ÿผ ์ž๋ฐ”์—์„œ ์ œ๊ณตํ•ด์ฃผ๋Š” util์„ ์ž˜ ํ™œ์šฉํ•˜์ง€ ๋ชปํ•œ ๊ฒƒ ๊ฐ™๋‹ค.. (๋ตํ‚นํ•˜์ž!)
53+
54+
์ฒ˜์Œ ์„ฑ๊ณตํ•œ ์†”๋ฃจ์…˜ ์ ‘๊ทผ๋ฒ•์€ ์ข‹์•˜๋Š”๋ฐ ์™œ ์„ฑ๋Šฅ์ด ์•ˆ๋‚˜์™”๋‚˜..
55+
HashMap์€ ๋‚ด๋ถ€์ ์œผ๋กœ ํ•ด์‹œ ํ…Œ์ด๋ธ” ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ, ๋™์ผํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๋”๋ผ๋„ ๋ฐฐ์—ด๋ณด๋‹ค ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ๋” ๋งŽ์ด ์‚ฌ์šฉํ•œ๋‹ค.
56+
๋˜ํ•œ, ํ‚ค์™€ ๊ฐ’์„ ๊ฐ์ฒด ํƒ€์ž…์œผ๋กœ ์ €์žฅํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์˜คํ† ๋ฐ•์‹ฑ/์–ธ๋ฐ•์‹ฑ ๋น„์šฉ์ด ๋ฐœ์ƒํ•˜๊ณ , ํ•ด์‹œ ๊ณ„์‚ฐ๊ณผ ์ถฉ๋Œ ์ฒ˜๋ฆฌ ๋“ฑ์˜ ์ถ”๊ฐ€ ์—ฐ์‚ฐ์ด ํ•„์š”ํ•˜๋‹ค.
57+
๋”ฐ๋ผ์„œ ๋ฐฐ์—ด์— ๋น„ํ•ด ๋А๋ฆฐ ๊ฒƒ ๊ฐ™๋‹ค.
58+
*/
59+
class Solution {
60+
public boolean isAnagram(String s, String t) {
61+
if (s.length() != t.length()) {
62+
return false;
63+
}
64+
65+
int[] counting = new int[26];
66+
for (char ch : s.toCharArray()) {
67+
counting[ch - 'a']++;
68+
}
69+
for (char ch : t.toCharArray()) {
70+
counting[ch - 'a']--;
71+
}
72+
73+
for (int count : counting) {
74+
if (count != 0) {
75+
return false;
76+
}
77+
}
78+
return true;
79+
}
80+
}

0 commit comments

Comments
ย (0)