您的位置 首页 技术

java如何实现字符串压缩

使用双指针进行字符串压缩 实例: public static void zipStr(String str) {char[] c = str.toCharArray();int i…

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

实例:

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++;}}

结果如图:

1ca02c4dab8b735107541403fcd2ddf.png

(推荐教程:java快速入门)

说明:该方法对于形如(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值为0if (!map.containsKey(c[i])) {map.put(c[i], 1);} else {map.put(c[i], count + 1);}}return map;}

结果如图:

e66e541f92ff932a89a47096ea06866.png

相关视频教程推荐:java视频教程

以上就是java如何实现字符串压缩的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/51942.html

为您推荐

返回顶部