首页 > 其他 > 详细

[Algo] 611. Compress String II

时间:2020-02-21 15:27:50      阅读:54      评论:0      收藏:0      [点我收藏+]

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();
  }
}

 

[Algo] 611. Compress String II

原文:https://www.cnblogs.com/xuanlu/p/12340765.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!