一种字符串压缩表示的解压
标题:一种字符串压缩表示的解压 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
有一种简易压缩算法:针对全部由小写英文字母组成的字符串,将其中连续超过两个相同字母的部分压缩为连续个数加该字母,其他部分保持原样不变。例如:字符串“aaabbccccd”经过压缩成为字符串“3abb4cd”。 请您编写解压函数,根据输入的字符串,判断其是否为合法压缩过的字符串,若输入合法则输出解压缩后的字符串,否则输出字符串“!error”来报告错误
import java.util.Scanner;
public class Main {
public static boolean isD(char c) {
return c >= '0' && c <= '9';
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
StringBuilder res = new StringBuilder();
char last = 0;
int len = 0;
int same = 0;
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (!isD(c)) {
if (c > 'z' || c < 'a') {
System.out.println("!error");
return;
}
}
//判断相同的字符出现三次则error
if (c == last) {
same++;
if (same >= 3 || len >= 1) {
System.out.println("!error");
return;
}
} else if (!isD(c)) {
same = 1;
last = c;
}
//如果是循环字符则直接拼接
if ((!isD(c)) && len != 0) {
// if (c == last) {
// System.out.println("!error");
// return;
// }
if (len <= 2) {
System.out.println("!error");
return;
}
for (int j = 0; j < len; ++j) {
res.append(c);
}
len = 0;
last = c;
continue;
} else if ((!isD(c)) && len == 0) {
res.append(c);
}
//如果是数字
if (c >= '0' && c <= '9') {
int t = c - '0';
//数字以0开头则error
if (c == '0' && len == 0) {
System.out.println("!error");
return;
} else {
len = len * 10 + c - '0';
}
}
}
System.out.println(res.toString());
}
}

