Skip to content

Commit 7f075e3

Browse files
committed
program to check if input string is valid anagram
1 parent 810fdd6 commit 7f075e3

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

Others/validAnagram.java

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
/**
5+
* Created by Dungeoun on 10/2/16.
6+
*/
7+
8+
9+
10+
public class Solution {
11+
12+
public static boolean isAnagram(String s, String t) {
13+
14+
15+
HashMap<Character, Integer> hash1 = new HashMap<>();
16+
17+
HashMap<Character, Integer> hash2 = new HashMap<>();
18+
19+
boolean a = false;
20+
21+
22+
for (int i = 0; i < s.length(); i++) {
23+
24+
if (hash1.containsKey(s.charAt(i)) == false) {
25+
26+
hash1.put(s.charAt(i), 1);
27+
28+
} else {
29+
30+
hash1.put(s.charAt(i), hash1.get(s.charAt(i)) + 1);
31+
32+
}
33+
34+
}
35+
36+
for (int i = 0; i < t.length(); i++) {
37+
38+
if (hash2.containsKey(t.charAt(i)) == false) {
39+
40+
hash2.put(t.charAt(i), 1);
41+
42+
} else {
43+
44+
hash2.put(t.charAt(i), hash2.get(t.charAt(i)) + 1);
45+
46+
}
47+
48+
}
49+
50+
51+
if(hash1.size()!=hash2.size()){
52+
a = false;
53+
}
54+
55+
else if((hash1.size()==0 && hash2.size()==0) ) {
56+
a = true;
57+
}
58+
else if(hash1.size()!=hash2.size()){
59+
a = false;
60+
}
61+
62+
else {
63+
for (Map.Entry<Character, Integer> entry : hash1.entrySet()) {
64+
65+
66+
if (hash2.containsKey(entry.getKey()) == true && hash2.get(entry.getKey()) == entry.getValue()) {
67+
68+
a = true;
69+
70+
}
71+
else {
72+
a = false;
73+
break;
74+
}
75+
76+
}
77+
}
78+
return a;
79+
80+
}
81+
82+
public static void main( String []args){
83+
84+
boolean b = isAnagram("a","ab");
85+
86+
System.out.println(b);
87+
88+
}
89+
}

0 commit comments

Comments
 (0)