Cracking the coding interview--Q1.5

原文

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become
a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.

译文

利用计算字符个数的方式实现一种基本的字符串压缩函数。例如字符串"aabcccccaaa"将变成"a2blc5a3"。如果经过压缩的字符串不比原来的字符串短的话,应该返回原字符串。

解答

没什么好说的,直接模拟题目的要求就行了。

public class Main {

    public static String compression (String str) {
        StringBuilder sb = new StringBuilder();
        int ct, pt = 0;
        int len = str.length();
        while(pt < len) {
            char ch = str.charAt(pt);
            ct = 1;
            for(int i = pt + 1 ; i < len; i++) {
                if(str.charAt(i) == ch)
                    ct++;
                else
                    break;
            }
            sb.append(ch).append(ct);
            pt += ct;
        }
        String res = sb.toString();
        if(res.length() < len)
            return res;
        else
            return str;
    }
        
    public static void main(String args[]) {
        String s1 = "aabcccccaaa";
        String s2 = "aab";
        System.out.println(compression(s1));
        System.out.println(compression(s2));
    }
}

 

posted on 2013-07-12 15:02 长颈鹿Giraffe 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/giraffe/p/3186337.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值