-
Notifications
You must be signed in to change notification settings - Fork 4
/
PermutationOfStringWithDuplicate.java
80 lines (66 loc) · 2.64 KB
/
PermutationOfStringWithDuplicate.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
package com.hrishikeshmishra.practices.recursion;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static com.hrishikeshmishra.practices.recursion.PermutationOfStringWithDuplicate.getPermutations;
/**
* Problem:
* Permutation of a String Duplicate
* All permutation of a string that has duplicate characters and lexicographic order.
* ;
* ;
* Algorithm:
* - If level is equal to size string then
* - - add character array to permutation list
* - - return
* - Iterate character count map
* - - If count of character is greater than zero then
* - - - add character to character array
* - - - decrease character count
* - - - recursively call with level + 1
* - - - reset character count
*
* @author hrishikesh.mishra
* @video https://www.youtube.com/watch?v=nYFd7VHKyWQ
* @link http://hrishikeshmishra.com/permutation-string-duplicate/
*/
public class PermutationOfStringWithDuplicate {
public static List<String> getPermutations(String string) {
Map<Character, Integer> characterCounts = getCharacterCounts(string);
List<String> permutations = new ArrayList<>();
getPermutations(characterCounts, 0, new char[string.length()], string.length(), permutations);
return permutations;
}
private static void getPermutations(Map<Character, Integer> characterCounts, int level, char[] characterArray,
int size, List<String> permutations) {
if (level == size) {
permutations.add(String.copyValueOf(characterArray));
return;
}
for (Map.Entry<Character, Integer> entry : characterCounts.entrySet()) {
if (entry.getValue() > 0) {
characterArray[level] = entry.getKey();
entry.setValue(entry.getValue() - 1);
getPermutations(characterCounts, level + 1, characterArray, size, permutations);
entry.setValue(entry.getValue() + 1);
}
}
}
private static Map<Character, Integer> getCharacterCounts(String string) {
Map<Character, Integer> characterCounts = new TreeMap<>();
for (Character character : string.toCharArray()) {
if (characterCounts.containsKey(character)) {
characterCounts.put(character, characterCounts.get(character) + 1);
} else {
characterCounts.put(character, 1);
}
}
return characterCounts;
}
}
class PermutationOfStringWithDuplicateTest {
public static void main(String[] args) {
System.out.println("Permutations of \"CAAB\": " + getPermutations("CAAB"));
}
}