zoukankan      html  css  js  c++  java
  • [Algo] 175. Decompress String II

    Given a string in compressed form, decompress it to the original string. The adjacent repeated characters in the original string are compressed to have the character followed by the number of repeated occurrences.

    Assumptions

    • The string is not null

    • The characters used in the original string are guaranteed to be ‘a’ - ‘z’

    • There are no adjacent repeated characters with length > 9

    Examples

    • “a1c0b2c4” → “abbcccc”

    public class Solution {
      public String decompress(String input) {
        // Write your solution here
        if (input.length() == 0) {
          return input;
        }
        StringBuilder sb = new StringBuilder();
        int i = 0;
        char[] charArr = input.toCharArray();
        char prevChar = input.charAt(0);
        while (i < charArr.length) {
          char cur = charArr[i];
          if (Character.isLetter(cur)) {
            prevChar = cur;
            i += 1;
          } else if (Character.isDigit(cur)) {
            int num = cur - '0';
            if (num == 0) {
              i += 1;
            } else {
              while (i + 1 < charArr.length && Character.isDigit(charArr[i + 1])) {
                num = 10 * num + (charArr[i + 1] - '0');
                i += 1;
              }
              for (int j = 0; j < num; j++) {
                sb.append(prevChar);
              }
              i += 1;
            }
          }
        }
        return sb.toString();
      }
    }
    public class Solution {
      public String decompress(String input) {
        // Write your solution here
        char[] charArr = input.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < charArr.length; i++) {
          char cur = charArr[i++];
          int num = charArr[i] - '0';
          for (int j = 0; j < num; j++) {
            sb.append(cur);
          }
        }
        return sb.toString();
      }
    }
  • 相关阅读:
    C++ 学习笔记
    面向对象
    多线程
    Spring-扫描注解原理,注解自动扫描原理分析
    Eclipse 中报错的阅读顺序
    Eclipse 常用技巧及常见问题解决
    JAVA高级复习-自定义泛型类、泛型接口的注意点
    JAVA高级复习-泛型的使用
    IntelliJ IDEA学习笔记连载一IntelliJ IDEA中创建Maven工程
    JAVA高级复习-多线程的创建方式二
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12340712.html
Copyright © 2011-2022 走看看