LC.604. Design Compressed String Iterator

LC.604. Design Compressed String Iterator_第1张图片

class StringIterator1(object):

    def __init__(self, compressedString):
        """
        :type compressedString: str
        """
        self.index = 0
        self.count = []
        self.char = []
        compressedString = compressedString + 'a'
        stack = []
        for cr in compressedString:
            if cr.isalpha():
                if len(stack):
                    self.count.append(int(''.join(stack)))
                self.char.append(cr)
                stack= []
            else:
                stack.append(cr)
        self.char = self.char[:-1]

    def next(self):
        """
        没有下一个元素要返回一个空格
        """
        if self.index == len(self.char):
            return ""
        res = self.char[self.index]
        self.count[self.index] -= 1
        if self.count[self.index] == 0:
            self.index += 1
        return res

    def hasNext(self):
        """
        :rtype: bool
        """
        return self.index != len(self.char)

class StringIterator(object):

    def __init__(self, compressedString):
        """
        用一个队列就行了
        """
        from collections import deque
        self.queue = deque()
        index = 0
        count = ""
        while index < len(compressedString):
            if compressedString[index].isalpha():
                if len(count):
                    self.queue.append(int(count))
                    count = ""
                self.queue.append(compressedString[index])
            else:
                count += compressedString[index]
            index += 1
        self.queue.append(int(count))
        print(self.queue)

    def next(self):
        """
        没有下一个元素要返回一个空格
        """
        if len(self.queue) == 0:
            return ' '
        res = self.queue[0]
        self.queue[1] -= 1
        if self.queue[1] == 0:
            self.queue.popleft()
            self.queue.popleft()
        return res

    def hasNext(self):
        """
        :rtype: bool
        """
        return len(self.queue) != 0

你可能感兴趣的:(LeetCode)