Problem
Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.
Implement the StringIterator class:
next()
Returns the next character if the original string still has uncompressed characters, otherwise returns a white space.hasNext()
Returns true if there is any letter needs to be uncompressed in the original string, otherwise returnsfalse
.
Example 1:
1 | Input |
Constraints:
1 <= compressedString.length <= 1000
compressedString
consists of lower-case an upper-case English letters and digits.- The number of a single character repetitions in
compressedString
is in the range[1, 10^9]
- At most
100
calls will be made tonext
andhasNext
.
Analysis
这是一道iterator的题目,也是实现next
和hasNext
两个方法。这种题目实现的方法有很多,比如在构造函数就处理好,或者按需计算等等。通常来说面试都是需要按需计算,这里我也用这种解法。首先我要把原始的compressedString
存下来,然后我还有两个变量,一个是idx
,指向当前的字符,还有一个是count
,表明当前字符还有多少个。
每次我都从idx + 1
开始计算,把count
计算出来,注意这里的count
可能是多位的,所以要用循环。然后每次next
时,count
自减1,如果减到为0,则需要移动idx
。idx
的移动需要跳过所有的数字,直到下一个字符。
hasNext
就比较简单了,直接判断idx
和字符串的长度就可以了。
Solution
无。
Code
1 | class StringIterator { |
Summary
这道题目还算是比较常规的iterator题目,算是见多一种类型。这道题目的分享到这里,感谢你的支持!