Skip to content

Commit 47a94f8

Browse files
authored
anagram from a string
a stand alone java program to create all the possible combination from a string
1 parent da7afbd commit 47a94f8

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Anagram.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package org.hacker.rank;
2+
3+
import java.util.Map;
4+
import java.util.TreeMap;
5+
6+
public class Anagram {
7+
8+
public static void main(String[] args) {
9+
String input = "abc";
10+
11+
// Create map to find the unique aphabets and count
12+
Map<Character, Integer> dataMap = new TreeMap<>();
13+
for(int i = 0; i <input.length(); i++) {
14+
if (dataMap.containsKey(input.charAt(i))) {
15+
dataMap.put(input.charAt(i), dataMap.get(input.charAt(i)) + 1);
16+
}
17+
else {
18+
dataMap.put(input.charAt(i), 1);
19+
}
20+
}
21+
22+
// character array to hold the characters
23+
char[] chars = new char[dataMap.size()];
24+
25+
// integer array to hold the count of the character
26+
int[] count = new int[dataMap.size()];
27+
28+
int index = 0;
29+
30+
for(Map.Entry<Character, Integer> entry : dataMap.entrySet()) {
31+
chars[index] = entry.getKey();
32+
count[index] = entry.getValue();
33+
index++;
34+
}
35+
36+
char[] container = new char[input.length()];
37+
anagram(chars, count, container, 0);
38+
}
39+
40+
// recursively find the anagram
41+
public static void anagram(char[] chars, int[] count, char[] result, int level){
42+
if (level == result.length) {
43+
print(result);
44+
return;
45+
}
46+
for (int i = 0; i < count.length; i++) {
47+
if(count[i] == 0) continue;
48+
count[i]--;
49+
result[level] = chars[i];
50+
anagram(chars, count, result, level + 1);
51+
count[i]++;
52+
}
53+
}
54+
55+
public static void print(char[] ch) {
56+
for(char c : ch) {
57+
System.out.print(c);
58+
}
59+
System.out.println("");
60+
}
61+
}

0 commit comments

Comments
 (0)