dcddc

西米大人的博客

0%

打印[]对

题目描述

对于[ [ [ ] ] [ ] ],打印:
+—–+
|+—+|
|+-+|
| |

| |
|+-+|
|+—+|
+-+
| |

| |
+-+
+—–+
对于[][],打印:
+-+
| |

| |
+-+
+-+
| |

| |
+-+
请根据输入的[]配对,打印恰当的图形

思路

用一个栈记录[出现的次数,碰到]时,将计数器pop出list
根据计数器的值,打印图形,并将每行打印push到另一个栈里(因为图形对称,所以栈保存后半部分的内容)
每次碰到从]变到[时,栈里添加一个新的计数器

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public static void main(String[] args) {
Stack<Integer> list = new Stack<>();
Stack<String> strings = new Stack<>(); // 为了对称输出,保存下半部分
list.push(0);
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
boolean isContinue = true; // 碰到]为false
for(int i = 0; i < string.length(); i++) {
char tmp = string.charAt(i);
if (isContinue) {
if(tmp == '[') { // 连续[,更新计数器
list.set(list.size()-1, list.peek()+1);
}else { // 碰到],即出现配对
isContinue = false;
int count = list.pop();
if(count == 1) { // 最近的配对[]只有一个[, 直接打印
System.out.println("+-+");
System.out.println("| |");
System.out.println();
System.out.println("| |");
System.out.println("+-+");
continue;
}

// 配对超过一个[的字符串输出
String string2 = "+";
for(int j = 0; j < 2*count - 1; j++) {
string2 += "-";
}
string2 += "+";
System.out.println(string2);
strings.push(string2);
count--;
while(count > 1) {
string2 = "|+";
for(int j = 0; j < 2*count - 1; j++) {
string2 += "-";
}
string2 += "+|";
System.out.println(string2);
strings.push(string2);
count--;
}
if(string.charAt(i+1) == ']') { // 连续]时,最内层的[]代表的字符串要加"|"
System.out.println("|+-+|");
System.out.println("| |");
System.out.println();
System.out.println("| |");
System.out.println("|+-+|");
}else {
System.out.println("+-+");
System.out.println("| |");
System.out.println();
System.out.println("| |");
System.out.println("+-+");
}
}
}else { // 前一个是]
if(tmp == '[') { // 添加新的配对计数器
list.push(1);
isContinue = true;
}else {
System.out.println(strings.pop());
}
}

}
}

考察点