Java Solution [not short]


  • 0

    leverage the Iterator.
    The harder part is to split compressedString to char:int pair.

    public class StringIterator {
        
        Iterator<Item> iter;
        Item cur;
        public StringIterator(String str) {
          List<Item> list = new ArrayList();
          String pren = null;
          char prec = ' ';
          
          for(char c: str.toCharArray()){
            if(Character.isLetter(c)){
              if(pren != null){
                list.add(new Item(prec, Integer.parseInt(pren)));
              }  
              prec = c;
              pren = "";
            }else{
              pren += c;    
            }  
          }  
          
          list.add(new Item(prec, Integer.parseInt(pren)));
          iter = list.iterator();
          if(iter.hasNext()) cur = iter.next();
        }
        
        public char next() {
          if(cur == null) return ' ';
          else {
            char res = cur.c;
            cur.n--;
            if(cur.n == 0){
              if(iter.hasNext()) cur = iter.next();
              else cur = null;
            }
            return res;
          }
        }
        
        public boolean hasNext() {
          if(cur != null) return true;
          else return false;
        }
    }
    
    class Item{
      char c;
      int n;
      Item(char cc, int nn){
        c = cc;
        n = nn;
      }
    }

Log in to reply
 

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