CC_6th--Q1.6

1.6 String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).

public static String compress(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); ) {
            int j = i + 1;
            char curr = s.charAt(i);
            while (j < s.length() && s.charAt(j) == curr) ++j;
            int count = j - i;
            sb.append(curr+String.valueOf(count));
            i = j;
        }
        return sb.length() < s.length() ? sb.toString() : s;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,934评论 0 23
  • 我喜欢 去掉所有修饰的诗 每一个字 都是一根骨 它支撑整个生命 即使埋在土里 也一直是最初的样子
    顽尘阅读 286评论 0 4
  • 寫在情人節前 《花瓜繞囗令》 老婆是瓜,情人是花, 累了看瓜,閑了赏花, 种瓜得瓜,养花有花, 瓜别想花,花勿念瓜...
    独行彡阅读 544评论 0 0
  • 据媒体报道,俄罗斯一架苏-24战机在叙利亚境内坠落。土耳其方面称,系其战机击落。俄方初步表态,指战机被土耳其击落。...
    南山GUSHI阅读 299评论 0 0
  • 今天下午16:30,在德国举行的2017年世乒赛单打就要鸣锣开战了,这届世乒赛受到全国乒乓球爱好者的追捧,我的几个...
    我是仙儿阅读 366评论 0 4