Classic way to solve iterator problem by using 'staging area', easy to read Java code


  • 0
    A
    public class StringIterator {
        // algorithm 2017/06/11: remember the current string, the current char, and count of current char in a staging area
        public StringIterator(String compressedString) {
            m_compressedString = compressedString;
            // no need to kick start as hasNext() will decompress the first char 
            // (and next() invokes hasNext())
        }
    
        public char next() {
            if (hasNext()) {
                assert 0 < m_currentCharCount;
                m_currentCharCount--;
            } else {
                assert ' ' == m_currentChar;
            }
            return m_currentChar;
        }
    
        public boolean hasNext() {
            if (0 < m_currentCharCount) {
                return true;
            } else {
                decompressOneChar();
                return 0 < m_currentCharCount;
            }
        }
    
        private void decompressOneChar() {
            int strLen = m_compressedString.length();
            if (0 < strLen) {
                m_currentChar = m_compressedString.charAt(0);
    
                int charCount = 0;
                int index     = 1;
                for (; index < strLen; index++) {
                    char ch = m_compressedString.charAt(index);
                    if (ch >= '0' && ch <= '9') {
                        charCount = charCount * 10 + (ch - '0');
                    } else {
                        break;
                    }
                }
                m_currentCharCount = charCount;
    
                // mutate the compressedString as the first char has been 'decompressed' and transferred out
                m_compressedString = m_compressedString.substring(index);
            } else {
                // no more chars?
                m_currentChar      = ' ';
                m_currentCharCount = 0;
            }
        }
    
        private String m_compressedString;
        private char   m_currentChar;
        private int    m_currentCharCount;
    }

Log in to reply
 

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