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

更新于: 2020年4月30日

446 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.