-
Notifications
You must be signed in to change notification settings - Fork 5
/
Day-13 Iterator for Combination
63 lines (51 loc) · 1.48 KB
/
Day-13 Iterator for Combination
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
class CombinationIterator {
int p=0;
List<String> c=null;
public CombinationIterator(String characters, int combinationLength) {
c=new ArrayList<>();
helper(characters,0,combinationLength,new StringBuilder());
}
public String next() {
return c.get(p++);
}
public boolean hasNext() {
return p<c.size();
}
void helper(String s,int pos,int combinationLength,StringBuilder sb){
if(sb.length()==combinationLength){
c.add(sb.toString());
return;
}
for(int i=pos;i<s.length();i++){
sb.append(s.charAt(i));
helper(s,i+1,combinationLength,sb);
sb.deleteCharAt(sb.length()-1);
}
}
}
class CombinationIterator {
int bitmask, n, k;
String chars;
public CombinationIterator(String characters, int combinationLength) {
n = characters.length();
k = combinationLength;
chars = characters;
bitmask = (1 << n) - (1 << n - k);
}
public String next() {
StringBuilder curr = new StringBuilder();
for (int j = 0; j < n; j++) {
if ((bitmask & (1 << n - j - 1)) != 0) {
curr.append(chars.charAt(j));
}
}
bitmask--;
while (bitmask > 0 && Integer.bitCount(bitmask) != k) {
bitmask--;
}
return curr.toString();
}
public boolean hasNext() {
return bitmask > 0;
}
}