zoukankan      html  css  js  c++  java
  • 1286. Iterator for Combination

    Design an Iterator class, which has:

    • A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
    • A function next() that returns the next combination of length combinationLength in lexicographical order.
    • A function hasNext() that returns True if and only if there exists a next combination.

    Example:

    CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator.
    
    iterator.next(); // returns "ab"
    iterator.hasNext(); // returns true
    iterator.next(); // returns "ac"
    iterator.hasNext(); // returns true
    iterator.next(); // returns "bc"
    iterator.hasNext(); // returns false
    

    Constraints:

    • 1 <= combinationLength <= characters.length <= 15
    • There will be at most 10^4 function calls per test.
    • It's guaranteed that all calls of the function next are valid.
    class CombinationIterator {
    
    PriorityQueue<String> pq = new PriorityQueue<>();
        public CombinationIterator(String s, int k) {
            generateSub(s,k,0,new StringBuilder());
        }
        private void generateSub(String s ,int len,int start,StringBuilder result) {
            if (len == 0){
                pq.add(result.toString());
                return;
            }
            for (int i = start; i <= s.length()-len; i++){
                result.append(s.charAt(i));
                generateSub(s, len-1, i+1, result);
                result.deleteCharAt(result.length()-1);
            }
        }
        public String next() {
            return pq.poll();
        }
        public boolean hasNext() {
            return !pq.isEmpty();
        }
    }
    class CombinationIterator {
    
        Queue<String> qu = new LinkedList();
        String orig = "";
        public CombinationIterator(String characters, int combinationLength) {
            orig = characters;
            find("", 0, combinationLength);
        }
        
        void find(String str, int index, int len) {
            if(len ==0) {
                qu.add(str);
                return;
            }
            for(int i= index; i<orig.length(); i++) {
                char ch = orig.charAt(i);
                find(str+ch , i+1, len-1);
            }
            
        }
        
        public String next() {
            if(!qu.isEmpty()) {
                return qu.poll();
            }
            return "";
        }
        
        public boolean hasNext() {
            return !qu.isEmpty();
        }
    }
  • 相关阅读:
    MFC中添加ToolTip提示框
    神经网络算法程序
    DOS命令大全(经典收藏)
    axure团队合作开发原型图
    POJ 3233 Matrix Power Series(矩阵高速功率+二分法)
    了解你的家公家IP
    HDOJ 3518 Boring counting
    模板方法模式的房间改造-组合查询
    6最好的之一 HTML5/CSS3 演示(PPT)框架
    试想一下,在代码学习Swift!
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12078968.html
Copyright © 2011-2022 走看看