Design compressed string iterator

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 ' '


**

class StringIterator {
    ArrayList<Long> cnt = new ArrayList<>();
    ArrayList<Character> chars = new ArrayList<>();
    int count = 0; //use count to specify how many chars have been iterated
    int pos = 0; //use position to specify the position of chars that needs to be returned
    public StringIterator(String compressedString) {
        char[] str = compressedString.toCharArray();
        //use time to mark which char I am calculating in this while loop
        int time = 0;
        //use slow to mark the char, and fast pointer to mark the char I am exploring
        int slow = 0, fast = 0;
        while(fast < str.length) {
            //each while loop focuses on solving one char and calculating one char's length
            cnt.add((long)0);
            chars.add(str[slow]);
            fast++;
            while (fast < str.length && str[fast] < 58 && str[fast] > 47) {
                cnt.set(time, cnt.get(time)*10+str[fast++]-'0');
            }
            if(fast<str.length) {
                slow = fast;
                time++;
            }
        }
        for(int i = 1; i < cnt.size(); i++) {
            cnt.set(i, cnt.get(i)+cnt.get(i-1));
        }
        for(char c: chars) {
            System.out.println(c);
        }
    }
    
    public char next() {
        if(hasNext()) {
            count++;
            if(count > cnt.get(pos)) {
                return chars.get(++pos);
            }else{
                return chars.get(pos);
            } 
        }
        return ' ';
    }
    
    public boolean hasNext() {
        return (count < cnt.get(cnt.size()-1));
    }
}
/**
 * Your StringIterator object will be instantiated and called as such:
 * StringIterator obj = new StringIterator(compressedString);
 * char param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */

Performance Analysis

  • The space required for storing the results of the precomputation is O(n)O(n), where nn refers to the length of the compressed string. The numsnums and charschars array contain a total of nn elements.
  • The precomputation step requires O(n)O(n) time. Thus, if hasNext() operation is performed most of the times, this precomputation turns out to be non-advantageous.
  • Once the precomputation has been done, hasNext() and next() requires O(1)O(1) time.
  • This approach can be extended to include the previous() and hasPrevious() operations, but that would require making some simple modifications to the current implementation.

Approach #3 Demand-Computation [Accepted]

Algorithm

In this approach, we don't make use of regex for finding the individual components of the given compressedStringcompressedString. We do not perform any form of precomputation. Whenever an operation needs to be performed, the required results are generated from the scratch. Thus, the operations are performed only on demand.

Let's look at the implementation of the required operations:

  1. next(): We make use of a global pointer ptrptr to keep a track of which compressed letter in the compressedStringcompressedString needs to be processed next. We also make use of a global variable numnum to keep a track of the number of instances of the current letter which are still pending. Whenever next() operation needs to be performed, firstly, we check if there are more uncompressed letters left in the compressedStringcompressedString. If not, we return a ' '. Otherwise, we check if there are more instances of the current letter still pending. If so, we directly decrement the count of instances indicated by numsnums and return the current letter. But, if there aren't more instances pending for the current letter, we update the ptrptr to point to the next letter in the compressedStringcompressedString. We also update the numnum by obtaining the count for the next letter from the compressedStringcompressedString. This number is obtained by making use of decimal arithmetic.
  2. hasNext(): If the pointer ptrptr has reached beyond the last index of the compressedStringcompressedString and numnum becomes, it indicates that no more uncompressed letters exist in the compressed string. Hence, we return a False in this case. Otherwise, a True value is returned indicating that more compressed letters exist in the compressedStringcompressedString.
public class StringIterator {
    String res;
    int ptr = 0, num = 0;
    char ch = ' ';
    public StringIterator(String s) {
        res = s;
    }
    public char next() {
        if (!hasNext())
            return ' ';
        if (num == 0) {
            ch = res.charAt(ptr++);
            while (ptr < res.length() && Character.isDigit(res.charAt(ptr))) {
                num = num * 10 + res.charAt(ptr++) - '0';
            }
        }
        num--;
        return ch;
    }
    public boolean hasNext() {
        return ptr != res.length() || num != 0;
    }
}

Performance Analysis

  • Since no precomputation is done, constant space is required in this case.
  • The time required to perform next() operation is O(1)O(1).
  • The time required for hasNext() operation is O(1)O(1).
  • Since no precomputations are done, and hasNext() requires only O(1)O(1) time, this solution is advantageous if hasNext() operation is performed most of the times.
  • This approach can be extended to include previous() and hasPrevious() operationsm, but this will require the use of some additional variables.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子捎泻,更是在濱河造成了極大的恐慌,老刑警劉巖食侮,帶你破解...
    沈念sama閱讀 219,188評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件爱谁,死亡現(xiàn)場(chǎng)離奇詭異沟使,居然都是意外死亡瓶蝴,警方通過(guò)查閱死者的電腦和手機(jī)毒返,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)舷手,“玉大人拧簸,你說(shuō)我怎么就攤上這事∧锌撸” “怎么了盆赤?”我有些...
    開(kāi)封第一講書人閱讀 165,562評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)蝎宇。 經(jīng)常有香客問(wèn)我,道長(zhǎng)祷安,這世上最難降的妖魔是什么姥芥? 我笑而不...
    開(kāi)封第一講書人閱讀 58,893評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮汇鞭,結(jié)果婚禮上凉唐,老公的妹妹穿的比我還像新娘。我一直安慰自己霍骄,他們只是感情好台囱,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著读整,像睡著了一般簿训。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,708評(píng)論 1 305
  • 那天强品,我揣著相機(jī)與錄音膘侮,去河邊找鬼。 笑死的榛,一個(gè)胖子當(dāng)著我的面吹牛琼了,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播夫晌,決...
    沈念sama閱讀 40,430評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼雕薪,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了晓淀?” 一聲冷哼從身側(cè)響起所袁,我...
    開(kāi)封第一講書人閱讀 39,342評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎要糊,沒(méi)想到半個(gè)月后纲熏,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,801評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡锄俄,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評(píng)論 3 337
  • 正文 我和宋清朗相戀三年局劲,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片奶赠。...
    茶點(diǎn)故事閱讀 40,115評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡鱼填,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出毅戈,到底是詐尸還是另有隱情苹丸,我是刑警寧澤,帶...
    沈念sama閱讀 35,804評(píng)論 5 346
  • 正文 年R本政府宣布苇经,位于F島的核電站赘理,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏扇单。R本人自食惡果不足惜商模,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蜘澜。 院中可真熱鬧施流,春花似錦、人聲如沸鄙信。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,008評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)装诡。三九已至银受,卻和暖如春践盼,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蚓土。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,135評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工宏侍, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蜀漆。 一個(gè)月前我還...
    沈念sama閱讀 48,365評(píng)論 3 373
  • 正文 我出身青樓谅河,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親确丢。 傳聞我的和親對(duì)象是個(gè)殘疾皇子绷耍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評(píng)論 2 355