Skip to content

Commit 8cd5413

Browse files
authored
Merge pull request #111 from chipbk10/Others
Solve Problem 1286 - Iterator for combination
2 parents b47b45b + ea4f550 commit 8cd5413

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package others.design;
2+
3+
public class Problem1286_IteratorForCombination {
4+
5+
class CombinationIterator {
6+
String s, cur;
7+
int m, n;
8+
9+
public CombinationIterator(String characters, int combinationLength) {
10+
s = characters;
11+
m = combinationLength;
12+
n = s.length();
13+
}
14+
15+
public String next() {
16+
if (cur == null) cur = s.substring(0, m);
17+
else {
18+
int i = find();
19+
int j = binarySearch(0, n-1, cur.charAt(i));
20+
String left = (i == 0) ? "" : cur.substring(0, i);
21+
String right = s.substring(j+1, j+1+m-i);
22+
cur = left+right;
23+
}
24+
return cur;
25+
}
26+
27+
public boolean hasNext() {
28+
return cur == null || find() >= 0;
29+
}
30+
31+
private int find() {
32+
for (int i = m-1, j = n-1; i >= 0; i--, j--) {
33+
if (cur.charAt(i) != s.charAt(j)) return i;
34+
}
35+
return -1;
36+
}
37+
38+
private int binarySearch(int lo, int hi, char c) {
39+
int mid = lo + (hi-lo)/2;
40+
if (s.charAt(mid) > c) return binarySearch(lo, hi-1, c);
41+
if (s.charAt(mid) < c) return binarySearch(lo+1, hi, c);
42+
return mid;
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)