互逆的压缩与解压(洛谷P1319、P1320题题解,Java语言描述)
程序员文章站
2022-07-13 13:52:38
...
P1319题目要求
P1320题目要求
分析
这两个题啊,就是互逆过程嘛……
说白了就是统计0与1,将一个0-1点阵压缩为一串数值或者将一串数值复原为一个0-1点阵……
值得一提的是,其实StringBuilder处理结果是很好的,遇到结尾不需要空格的话直接toString()以后trim()一下就没了呢,很省事,根本不用多次输出或者多次字符串连接(+)……
0与1的话分开处理就行,遇到不同数值的时候处理一下就行……
看代码就很容易理解的……
P1319代码(Java语言描述)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] str_array = scanner.nextLine().split("\\s+");
scanner.close();
int num = Integer.parseInt(str_array[0]);
boolean zero = true;
StringBuilder tempString = new StringBuilder();
for (int i = 1; i < str_array.length; i++) {
int tempNum = Integer.parseInt(str_array[i]);
if (zero) {
for (int j = 0; j < tempNum; j++) {
tempString.append(0);
if (tempString.length() == num) {
System.out.println(tempString);
tempString = new StringBuilder();
}
}
} else {
for (int j = 0; j < tempNum; j++) {
tempString.append(1);
if (tempString.length() == num) {
System.out.println(tempString);
tempString = new StringBuilder();
}
}
}
//改变下一次的标记
if (zero) {
zero = false;
} else {
zero = true;
}
}
}
}
P1320代码(Java语言描述)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String firstLine = scanner.nextLine();
int num = firstLine.length(), tempCounter = 0;
boolean zero = true;
String[] array = new String[num];
array[0] = firstLine;
for (int i = 1; i < num; i++) {
array[i] = scanner.nextLine();
}
scanner.close();
StringBuilder builder = new StringBuilder(num + " ");
for (int i = 0; i < num; i++) {
char[] chars = array[i].toCharArray();
for (char c : chars) {
if (c == '0') {
if (zero) {
tempCounter++;
} else {
builder.append(tempCounter).append(" ");
tempCounter = 1;
zero = true;
}
} else {
if (zero) {
builder.append(tempCounter).append(" ");
tempCounter = 1;
zero = false;
} else {
tempCounter++;
}
}
}
}
if (tempCounter != 0) {
builder.append(tempCounter);
}
System.out.println(builder.toString().trim());
}
}