题目大致如下:
1. 请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
2. 根据压缩规则编写函数对压缩后的字符串进行解压缩
压缩规则:
1、仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc"。
2、压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"。
实现代码(Java)如下:
public class ZipChar {
private static final String TAG = "ZipChar";
public static void main(String[] args) {
String str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaavcsdssssdfvvvvv";
System.out.println(compressChar(str));
System.out.println(decompressChar(compressChar(str)));
}
private static String compressChar(String str) {
StringBuilder sb = new StringBuilder();
char[] chars = str.toCharArray();
int count = 1;
int n = chars.length;
for (int i = 1; i < n; i++) {
if(chars[i] == chars[i-1]) {
count++;
} else {
if(count > 1) {
sb.append(count);
}
sb.append(chars[i-1]);
count = 1;
}
}
if(count > 1) {
sb.append(count);
sb.append(chars[n-1]);
}
return sb.toString();
}
private static String decompressChar(String str) {
StringBuilder sb = new StringBuilder();
char[] chars = str.toCharArray();
int count = 0;
for(int i = 0, n = chars.length; i < n; i++) {
if((chars[i] + "").matches("[0-9]")) {
count = count * 10 + Integer.parseInt(chars[i] + "");
} else if((chars[i] + "").matches("[a-z]")) {
if(count == 0) {
sb.append(chars[i]);
}
for(int j = 0; j < count; j++) {
sb.append(chars[i]);
}
count = 0;
}
}
return sb.toString();
}
}