C++ 中的組合迭代器
假設我們需要設計一個迭代器類,該類包含以下幾個操作:
- 定義一個建構函式,它接收一個排序後的、不重複的小寫英文字母字串和一個數字 combinationLength 作為引數。
- 定義一個函式 next(),該函式返回下一個長度為 combinationLength 的組合,按照字母順序排列。
- 定義另一個函式 hasNext(),當且僅當存在下一個組合時返回 True。
例如,如果輸入如下:
CombinationIterator iterator = new CombinationIterator("xyz", 2);
iterator.next(); // returns "xy"
iterator.hasNext(); // returns true
iterator.next(); // returns "xz"
iterator.hasNext(); // returns true
iterator.next(); // returns "yz"
iterator.hasNext(); // returns false為了解決這個問題,我們將遵循以下步驟:
- 建立一個字串陣列 comb 和一個索引 idx。
- 定義一個方法 makeCombs(),它將接收字串 s、整數變數 l、一個初始為空的臨時字串 temp 和一個初始為 0 的起始位置 start 作為引數。該方法定義如下:
- 如果 temp 的大小等於 l,則將 temp 插入到 comb 中並返回。
- 對於 i 的範圍從 start 到 s 的大小
- makeCombs(s, l, temp + s[i], i + 1)
- printVector() 方法將接收字串陣列作為輸入,它將顯示該陣列的元素。
- 定義建構函式如下:它將接收字串 c 和 cl 作為引數,
- 呼叫 makeCombs(c, cl),設定 idx := 0。
- next() 方法將增加 idx 並返回 comb[idx - 1]。
- hasNext() 方法將返回 true(如果 idx 不等於 comb 的大小),否則返回 false。
示例(C++)
讓我們看看以下實現,以便更好地理解:
#include <bits/stdc++.h>
using namespace std;
class CombinationIterator {
public:
vector <string> combs;
int idx;
void makeCombs(string s, int l, string temp ="", int start = 0){
if(temp.size() == l){
combs.push_back(temp);
return;
}
for(int i = start; i < s.size(); i++){
makeCombs(s, l, temp + s[i], i + 1);
}
}
void printVector(vector <string> v){
for(int i = 0; i < v.size(); i++){
cout << v[i] << "\n";
}
cout << endl;
}
CombinationIterator(string c, int cl) {
makeCombs(c, cl);
idx = 0;
}
string next() {
idx++;
return combs[idx - 1];
}
bool hasNext() {
return !(idx == combs.size());
}
};
main(){
CombinationIterator ob("xyz", 2);
cout << (ob.next()) << endl;
cout << (ob.hasNext()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext()) << endl;
}輸入
Initialize with “xyz” and 2, then call next() and hasNext() multiple times
輸出
xy 1 xz 1 yz 0
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP