search
HomeJavaJavagetting StartedHow to implement string compression in java

How to implement string compression in java

Mar 17, 2020 pm 05:37 PM
javastring

How to implement string compression in java

Use double pointers for string compression

Example:

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

The result is as shown in the figure:

How to implement string compression in java

(Recommended tutorial: java quick start)

Description: This method compresses a string in the form of (aaabbbccc), and the compression result is a3b3c3, But for the compression result of the form (acaadbbbcceeeffffff), the result is a1c1a2d1b3c2e3f6. Obviously, this result is unreasonable, so next use HashMap for string compression

Use HashMap for string compression

Example:

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

The result is as shown:

How to implement string compression in java

##Related video tutorial recommendation:

java video tutorial

The above is the detailed content of How to implement string compression in java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.