Skip to content

Commit ae647ca

Browse files
committed
Design Compressed String Iterator
1 parent a6e5bca commit ae647ca

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Design_Compressed_String_Iterator.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Design and implement a data structure for a compressed string iterator.
2+
# It should support the following operations: next and hasNext.
3+
#
4+
# The given compressed string will be in the form of each letter followed
5+
# by a positive integer representing the number of this letter existing in
6+
# the original uncompressed string.
7+
#
8+
# next() - if the original string still has uncompressed characters, return
9+
# the next letter; Otherwise return a white space.
10+
# hasNext() - Judge whether there is any letter needs to be uncompressed.
11+
#
12+
# Note:
13+
# Please remember to RESET your class variables declared in StringIterator,
14+
# as static/class variables are persisted across multiple test cases. Please see here for more details.
15+
#
16+
# Example:
17+
#
18+
# StringIterator iterator = new StringIterator("L1e2t1C1o1d1e1");
19+
#
20+
# iterator.next(); // return 'L'
21+
# iterator.next(); // return 'e'
22+
# iterator.next(); // return 'e'
23+
# iterator.next(); // return 't'
24+
# iterator.next(); // return 'C'
25+
# iterator.next(); // return 'o'
26+
# iterator.next(); // return 'd'
27+
# iterator.hasNext(); // return true
28+
# iterator.next(); // return 'e'
29+
# iterator.hasNext(); // return false
30+
# iterator.next(); // return ' '
31+
32+
33+
class StringIterator:
34+
35+
def __init__(self, compressedString):
36+
self.s = compressedString
37+
self.ptr = 0
38+
self.num = 0
39+
self.len = len(compressedString)
40+
self.char = ""
41+
42+
def next(self):
43+
if not self.hasNext():
44+
return ' '
45+
if self.num == 0:
46+
self.char = self.s[self.ptr]
47+
self.ptr = self.ptr + 1
48+
arr = []
49+
while self.ptr < self.len and self.s[self.ptr].isdigit():
50+
arr.append(self.s[self.ptr])
51+
self.ptr += 1
52+
arr = "".join(arr)
53+
self.num = int(arr) - 1
54+
return self.char
55+
else:
56+
self.num -= 1
57+
return self.char
58+
59+
def hasNext(self):
60+
if self.ptr >= self.len and self.num == 0:
61+
return False
62+
return True
63+
64+
# Your StringIterator object will be instantiated and called as such:
65+
# obj = StringIterator(compressedString)
66+
# param_1 = obj.next()
67+
# param_2 = obj.hasNext()

0 commit comments

Comments
 (0)