LeetCode 604. Design Compressed String Iterator
原题链接在这里:https://leetcode.com/problems/design-compressed-string-iterator/description/
题目:
Design and implement a data structure for a compressed string iterator. It should support the following operations: next
and hasNext
.
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.
next()
- if the original string still has uncompressed characters, return the next letter; Otherwise return a white space.hasNext()
- Judge whether there is any letter needs to be uncompressed.
Note:
Please remember to RESET your class variables declared in StringIterator, as static/class variables are persisted across multiple test cases. Please see here for more details.
Example:
StringIterator iterator = new StringIterator("L1e2t1C1o1d1e1"); iterator.next(); // return 'L' iterator.next(); // return 'e' iterator.next(); // return 'e' iterator.next(); // return 't' iterator.next(); // return 'C' iterator.next(); // return 'o' iterator.next(); // return 'd' iterator.hasNext(); // return true iterator.next(); // return 'e' iterator.hasNext(); // return false iterator.next(); // return ' '
题解:
用 index 标记当前s位置. 用count计数之前char出现的次数. 当count--到0时继续向后移动 index.
Time Complexity: hasNext(), O(1). next(), O(n). n= compressedString.length().
Space: O(1).
AC Java:
1 class StringIterator { 2 String s; 3 int index; 4 char cur; 5 int count; 6 7 public StringIterator(String compressedString) { 8 s = compressedString; 9 index = 0; 10 count = 0; 11 } 12 13 public char next() { 14 if(count != 0){ 15 count--; 16 return cur; 17 } 18 19 if(index >= s.length()){ 20 return ' '; 21 } 22 23 cur = s.charAt(index++); 24 int endIndex = index; 25 while(endIndex<s.length() && Character.isDigit(s.charAt(endIndex))){ 26 endIndex++; 27 } 28 29 count = Integer.valueOf(s.substring(index, endIndex)); 30 index = endIndex; 31 count--; 32 return cur; 33 } 34 35 public boolean hasNext() { 36 return index != s.length() || count != 0; 37 } 38 } 39 40 /** 41 * Your StringIterator object will be instantiated and called as such: 42 * StringIterator obj = new StringIterator(compressedString); 43 * char param_1 = obj.next(); 44 * boolean param_2 = obj.hasNext(); 45 */