[LeetCode] Iterator for Combination

1286. Iterator for Combination

Design the CombinationIterator class:

  • CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
  • next() Returns the next combination of length combinationLength in lexicographical order.
  • hasNext() Returns true if and only if there exists a next 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
class CombinationIterator {
vector<int> pos;
string s;
bool start = true;
void posNext() {
if(pos.back() != s.length() - 1) {
pos.back()++;
} else {
for(int i = pos.size() - 2; i >= 0; i--) {
if(pos[i] + 1 == pos[i+1]) continue;
pos[i]++;
for(int k = i + 1; k < pos.size(); k++) pos[k] = pos[k-1] + 1;
break;
}
}
}
public:
CombinationIterator(string characters, int combinationLength) : s(characters){
pos = vector<int>(combinationLength);
iota(begin(pos), end(pos), 0);
}

string next() {
if(!start) {
posNext();
}
string res = "";
for(auto& p : pos) res.push_back(s[p]);
start = false;
return res;
}

bool hasNext() {
if(start) return true;
return pos[0] != s.length() - pos.size();
}
};

/**
* 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();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/20/PS/LeetCode/iterator-for-combination/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.