Home > Java > Javagetting Started > How to implement string compression in java

How to implement string compression in java

王林
Release: 2020-03-17 17:37:47
forward
4211 people have browsed it

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++;
		}
	}
Copy after login

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;
	}
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template