• [Algo] 611. Compress String II


    Given a string, replace adjacent, repeated characters with 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’

    Examples

    • “abbcccdeee” → “a1b2c3d1e3”

    public class Solution {
      public String compress(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 count = 1;
          while (i + 1 < charArr.length && charArr[i + 1] == charArr[i]) {
            count += 1;
            i += 1;
          }
          sb.append(cur).append(count);
        }
        return sb.toString();
      }
    }
  • 相关阅读:
    模块3 re + 正则表达式
    模块2
    模块1
    super
    MRO,C3算法
    日志,固定格式
    异常处理,MD5
    类的约束
    反射
    异常处理MR5
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12340765.html
Copyright © 2020-2023  润新知