題目: LeetCode - 1286. Iterator for Combination

題目說明

設計一個 Class,並完成題目要求完成的函式。

  • CombinationIterator(string characters, int combinationLength):
    Constructor,characters 為排序好的字串並且每個字元只會出現一次,combinationLength 為組合的長度。
  • next(): 按照字典序返回長度為 combinationLength 的下一個排列。
  • hasNext(): 返回是否還能形成下一個排序。

解題思路

其實就是排序的問題,最小的情況就是 characters 的前 combinationLength 個字元,最大的情況就是 characters 的倒數 combinationLength 個字元。

  • CombinationIterator(string characters, int combinationLength): 在構造的時候我們把最小的情況放入 cur,最大的情況放入 last,並紀錄原本的 characterscombinationLength
  • next(): 更新 cur 即可。
  • hasNext(): 若是 cur != last 代表還能找出下一個排序。

參考解法

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
class CombinationIterator {
public:
CombinationIterator(string characters, int combinationLength) : orgin(characters), length(combinationLength), first(true) {
cur = characters.substr(0, combinationLength);
last = characters.substr(characters.size() - combinationLength);
}

string next() {
if(first) { first = false; return cur; }
int pos = cur.size() - 1;
while(cur[pos] == last[pos]) --pos;
int opos = 0;
while(cur[pos] != orgin[opos]) ++opos;
for(int i = pos; i < cur.size(); ++i)
cur[i] = orgin[opos + i + 1 - pos];
return cur;
}

bool hasNext() { return cur != last; }

private:
string orgin;
string cur;
string last;
int length;
bool first;
};