Short Python via regular expression

  • 0

    Using two indices self.i and self.j to indicates which tuple are we current looking at and how many of current character has been iterated.

    class StringIterator(object):
        def __init__(self, compressedString):
            :type compressedString: str
            self.i = self.j = 0
            self.chars = [(x[0], int(x[1:])) for x in re.findall(r"\w\d+", compressedString)]
            self.I = len(self.chars)
        def next(self):
            :rtype: str
            if not self.hasNext(): return ' '
            c = self.chars[self.i][0]
            self.j = (self.j+1) % self.chars[self.i][1]
            if not self.j: self.i += 1
            return c
        def hasNext(self):
            :rtype: bool
            return bool(self.chars) and self.i < self.I and self.j < self.chars[self.i][-1]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.