-
Notifications
You must be signed in to change notification settings - Fork 1
/
242. Valid Anagram.java
52 lines (38 loc) · 1 KB
/
242. Valid Anagram.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
//BRUTE FORCE APPROACH - nlogn
class Solution {
public boolean isAnagram(String s, String t) {
char arr[] = s.toCharArray();
char arr2[] = t.toCharArray();
Arrays.sort(arr);
Arrays.sort(arr2);
return Arrays.equals(arr,arr2);
}
}
//OPTIMAL APPROACH - O(n)
class Solution {
public boolean isAnagram(String s, String t) {
int words[] = new int[26];
for(int i=0;i<s.length();i++)
{
int index = s.charAt(i) - 'a';
words[index] = words[index] +1;
}
for(int i=0;i<t.length();i++)
{
int index = t.charAt(i) - 'a';
if(words[index]-1<0)
{
return false;
}
words[index ] = words[index]-1;
}
for(int i=0;i<words.length;i++)
{
if(words[i]!=0)
{
return false;
}
}
return true;
}
}