Java实现字符串压缩

使用双指针进行字符串压缩

public static void zipStr(String str) {
		char[] c = str.toCharArray();
		int index = 0;
		int num = 1;
		int len = c.length;
		while (index < len - 1) {
			while (c[index] == c[index + 1]) {
				num++;
				index++;
				if (index >= len - 1) {
					break;
				}
			}
			System.out.print(c[index]);
			System.out.print(num);
			num = 1;
			index++;
		}
	}

在这里插入图片描述
说明:该方法对于形如(aaabbbccc)的字符串进行压缩,压缩结果为a3b3c3,但是对于形如(acaadbbbcceeeffffff)压缩结果则为a1c1a2d1b3c2e3f6,显然这种结果是不合理的,因此接下来运用HashMap进行字符串压缩

使用HashMap进行字符串压缩

public static HashMap fun1(String str) {
		HashMap<Character, Integer> map = new HashMap<Character, Integer>();
		char[] c = str.toCharArray();
		for (int i = 0; i < c.length; i++) {
			Integer count = map.get(c[i]);//此处的count的类型一定要为Integer,如果为int类型,则count值为0
			if (!map.containsKey(c[i])) {
				map.put(c[i], 1);
			} else {
				map.put(c[i], count + 1);
			}
		}
		return map;
	}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值