字符串压缩 [#4]

问题:

把字符串压缩,比如aaabbbbc, 压缩后成为:a3b4c1。

分析:

这题很简单,我们只需要从头到尾遍历一遍字符串即可。首先设置一个计数器count, 每次“指针移位”的时候,判断当前字符是否与前一个字符相等,如果相等,count++, 指针继续下移,否则,我们需要对前面已经遍历的字符串进行处理,然后重新初始化count,直到字符串遍历结束。这题的关键是对最后一个字符的处理。

public static String compress(char[] array) {
		if (array == null || array.length == 0 ) return null;
		
		int count = 1;
		StringBuilder sb = new StringBuilder();  //save the compressed string
		
		for (int index = 1; index < array.length; index++) {
			if (array[index] == array[index - 1]) {
				count++;
			} else {
				sb.append(array[index - 1]);
				sb.append(count);
				count = 1;
			}
		}
		//important! add the last character to the stringbuilder.
		sb.append(array[array.length - 1]);
		sb.append(count);
		
		return sb.toString();
				
	}
扩展:
给定一个排序的整数数组,去除里面重复的值。比如:{1,1,1,1,2,2,5,5,5,} 变为 {1,2,5}。
转载请注明出处: http://blog.youkuaiyun.com/beiyeqingteng

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值