1
- /*
2
- Problem: https://leetcode.com/problems/valid-anagram/
3
- Description: return true if one string is an anagram of the other, one formed by rearranging the letters of the other
4
- Concept:String, Hash Table, Sorting, Array, Counting, String Matching, Ordered Map, Ordered Set, Hash Function ...
5
- Time Complexity: O(n), Runtime: 27ms
6
- Space Complexity: O(n), Memory: 43.05MB
7
- */
8
- import java .util .HashMap ;
9
- import java .util .Map ;
1
+ /**
2
+ * <a href="https://leetcode.com/problems/valid-anagram/">week02-1.valid-anagram</a>
3
+ * <li> Description: return true if one string is an anagram of the other, one formed by rearranging the letters of the other </li>
4
+ * <li> Concept:String, Hash Table, Sorting, Array, Counting, String Matching, Ordered Map, Ordered Set, Hash Function ... </li>
5
+ * <li> Time Complexity: O(n), Runtime: 15ms </li>
6
+ * <li> Space Complexity: O(n), Memory: 44.66MB </li>
7
+ */
10
8
11
9
class Solution {
12
10
public boolean isAnagram (String s , String t ) {
13
- if (s .length () != t .length ()) return false ;
11
+ if (s .length () != t .length ()) return false ;
14
12
15
- Map <Character , Integer > charCount = new HashMap <>();
16
- for ( int i = 0 ; i < s . length (); i ++){
17
- charCount . put ( s . charAt ( i ), charCount . getOrDefault ( s . charAt ( i ), 0 )+ 1 );
18
- charCount . put ( t . charAt ( i ), charCount . getOrDefault ( t . charAt ( i ), 0 )- 1 );
19
- }
20
- for ( Integer count : charCount . values ()){
21
- if ( count != 0 ) return false ;
22
- }
23
- return true ;
13
+ Map <Integer , Integer > tmap = t . chars ()
14
+ . boxed ()
15
+ . collect ( Collectors . toMap ( i -> i , i -> 1 , ( i1 , i2 ) -> i1 + i2 ) );
16
+
17
+ Map < Integer , Integer > smap = s . chars ()
18
+ . boxed ()
19
+ . collect ( Collectors . toMap ( i -> i , i -> 1 , ( i1 , i2 ) -> i1 + i2 )) ;
20
+
21
+ return tmap . equals ( smap ) ;
24
22
}
25
- }
23
+ }
0 commit comments