Home >Java >Javagetting Started >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:
(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:
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!