File tree Expand file tree Collapse file tree 1 file changed +18
-5
lines changed Expand file tree Collapse file tree 1 file changed +18
-5
lines changed Original file line number Diff line number Diff line change 4
4
*
5
5
* 공간 복잡도: O(N)
6
6
*
7
+ * 처음 문제를 보고 들었던 생각: 정렬 시켜서 같으면 anagram?
8
+ * -> 아, 그러면 등장한 문자의 빈도수가 같네?
9
+ * -> 결국 26 사이즈가 인풋에 영향을 받지 않으므로 공간 복잡도를 O(1)로 개선할 수 있고,
10
+ * -> 시간 복잡도도 O(N)으로 개선할 수 있겠다.
7
11
*/
8
12
class Solution {
9
13
public boolean isAnagram (String s , String t ) {
10
- char [] sChars = s .toCharArray ();
11
- char [] tChars = t .toCharArray ();
14
+ if (s .length () != t .length ()) return false ;
12
15
13
- Arrays .sort (sChars );
14
- Arrays .sort (tChars );
16
+ int [] charCount = new int [26 ];
15
17
16
- return Arrays .equals (sChars , tChars );
18
+ for (char c : s .toCharArray ()) {
19
+ charCount [c - 'a' ]++;
20
+ }
21
+
22
+ for (char c : t .toCharArray ()) {
23
+ charCount [c - 'a' ]--;
24
+ if (charCount [c - 'a' ] < 0 ) {
25
+ return false ;
26
+ }
27
+ }
28
+
29
+ return true ;
17
30
}
18
31
}
You can’t perform that action at this time.
0 commit comments