-
Notifications
You must be signed in to change notification settings - Fork 17
/
CheckAnagram.java
58 lines (56 loc) · 1.57 KB
/
CheckAnagram.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
package SummerTrainingGFG.Strings;
import java.util.HashMap;
/**
* @author Vishal Singh
*/
public class CheckAnagram {
/**
* Using Hash map*/
static boolean checkAnagram(String s1,String s2){
if (s1.length() != s2.length()){
return false;
}
HashMap<Character,Integer> set = new HashMap<>();
for (int i = 0; i < s1.length(); i++) {
if (set.containsKey(s1.charAt(i))){
set.put(s1.charAt(i),set.get(s1.charAt(i))+1);
}
else {
set.put(s1.charAt(i),1);
}
}
for (int i = 0; i < s2.length(); i++) {
if (set.containsKey(s2.charAt(i))){
set.put(s2.charAt(i),set.get(s2.charAt(i))-1);
if (set.get(s2.charAt(i)) == 0){
set.remove(s2.charAt(i));
}
}
}
return set.size() == 0;
}
/**
* Using Array*/
static boolean check(String s1,String s2){
if (s1.length() != s2.length()){
return false;
}
int[] count = new int[256];
for (int i = 0; i < s1.length(); i++) {
count[s1.charAt(i)]++;
count[s2.charAt(i)]--;
}
for (int i = 0; i < 256; i++) {
if (count[i] != 0){
return false;
}
}
return true;
}
public static void main(String[] args) {
String s1 = "vishal";
String s2 = "lahsiv";
System.out.println(checkAnagram(s1,s2));
System.out.println(check(s1,s2));
}
}