-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathValidAnagram.java
93 lines (65 loc) · 1.96 KB
/
ValidAnagram.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
Source: https://leetcode.com/problems/valid-anagram/
2 Approaches
1st Approach
Time: O(n), where n is the length of the given string(s)
Space: O(1), in-place, thought we are using an array(charFreq) of size 26, but it doesn't depend on the input
and will be constant for all the inputs.
Basic Idea:
- Count the frequency of each character in the given string(String s)
- Now, iterate through each character present in another string(String t).
If any character in String t is not present in String s
eg:
String s = "abc";
String t = "bcz";
Here, 'z' is not present in String s
OR
Count of some specific character in String t is more than those present in String s
eg:
String s = "aabc";
String t = "aaab";
Here, count of 'a' in String t is more than that present in String s
then, return false.
- If second string(String t) was completely iterated without returning false, then return true;
*/
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()) {
return false;
}
int[] charFreq = new int[26];
for(char sChar : s.toCharArray()) {
++charFreq[sChar - 'a'];
}
for(char tChar : t.toCharArray()) {
if(--charFreq[tChar - 'a'] < 0) {
return false;
}
}
return true;
}
}
/*
2nd Approach(Follow Up using Map)
Time: O(n), where n is the length of the given string(s)
Space: O(n), we need a map to store the characters(including unicode characters)
*/
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()) {
return false;
}
Map<Character, Integer> charFreq = new HashMap<>();
for(char sChar : s.toCharArray()) {
charFreq.put(sChar, charFreq.getOrDefault(sChar, 0) + 1);
}
for(char tChar : t.toCharArray()) {
Integer val = charFreq.get(tChar);
if(val == null || val == 0) {
return false;
}
charFreq.put(tChar, val - 1);
}
return true;
}
}