1286.字母組合迭代器

請你設計一個迭代器類,包括以下內容:

一個構造函數,輸入參數包括:一個 有序且字符唯一 的字符串 characters(該字符串只包含小寫英文字母)和一個數字 combinationLength 。
函數 next() ,按 字典序 返回長度爲 combinationLength 的下一個字母組合。
函數 hasNext() ,只有存在長度爲 combinationLength 的下一個字母組合時,才返回 True;否則,返回 False。
 

示例:

CombinationIterator iterator = new CombinationIterator("abc", 2); // 創建迭代器 iterator

iterator.next(); // 返回 "ab"
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 "ac"
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 "bc"
iterator.hasNext(); // 返回 false

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/iterator-for-combination
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

class CombinationIterator {
public:
    CombinationIterator(string characters, int combinationLength) {
        dfs(characters,combinationLength,0,"");
        reverse(paths.begin(),paths.end());
    }

    void dfs(string str,int len,int index,string path){
        if (path.size() == len) {
            paths.push_back(path);
            return;
        }

        for (int i = index; i < str.size(); i++) {
            dfs(str, len, i + 1, path + str[i]);
        }
    }
    
    string next() {
        string temp = paths[paths.size()-1];
        paths.pop_back();
        return temp;
    }
    
    bool hasNext() {
        return !paths.size()==0;
    }

private:
    vector<string> paths;
};

/**
 * 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();
 */

 

發佈了188 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章