-
Notifications
You must be signed in to change notification settings - Fork 111
/
1286. Iterator for Combination.cpp
61 lines (52 loc) · 1.81 KB
/
1286. Iterator for Combination.cpp
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
//Runtime: 20 ms, faster than 27.38% of C++ online submissions for Iterator for Combination.
//Memory Usage: 13.8 MB, less than 100.00% of C++ online submissions for Iterator for Combination.
class CombinationIterator {
public:
CombinationIterator(string characters, int combinationLength) {
this->characters = characters;
this->combinationLength = combinationLength;
for(int i = 0; i < combinationLength; i++){
comb.push_back(i);
}
}
string next() {
if(!hasNext()){
return cur;
}
string tmp;
tmp.clear();
for(int i = 0; i < combinationLength; i++){
tmp += characters[comb[i]];
}
cur = tmp;
//update comb
bool updated = false;
//start from tail
for(int i = combinationLength - 1; i >= 0; i--){
//if comb[i] is already the last possible character
if(comb[i] != characters.size() - 1 - (combinationLength - 1 - i)){
comb[i]++;
//move the later characters to the just left of current updated position
for(int j = i+1; j < combinationLength; j++){
comb[j] = comb[j-1]+1;
}
updated = true;
break;
}
}
return cur;
}
bool hasNext() {
return cur != characters.substr(characters.size() - combinationLength, combinationLength);
}
vector<int> comb;
string characters;
int combinationLength;
string cur;
};
/**
* Your CombinationIterator object will be instantiated and called as such:
* CombinationIterator* obj = new CombinationIterator(characters, combinationLength);
* string param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/