码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】1286. Iterator for Combination

时间:2019-12-15 10:24:14      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:cas   return   题目   you   struct   style   and   ret   nts   

题目如下:

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(object):

    def __init__(self, characters, combinationLength):
        """
        :type characters: str
        :type combinationLength: int
        """
        self.val = []
        from itertools import combinations
        for i in combinations(characters, combinationLength):
            self.val.append(‘‘.join(i))

    def next(self):
        """
        :rtype: str
        """
        return self.val.pop(0)
        

    def hasNext(self):
        """
        :rtype: bool
        """
        return len(self.val) > 0
        


# Your CombinationIterator object will be instantiated and called as such:
# obj = CombinationIterator(characters, combinationLength)
# param_1 = obj.next()
# param_2 = obj.hasNext()

 

【leetcode】1286. Iterator for Combination

标签:cas   return   题目   you   struct   style   and   ret   nts   

原文地址:https://www.cnblogs.com/seyjs/p/12041872.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!