中括号序列绘制(比较有意思)

来源:互联网 发布:手机影视剪辑软件 编辑:程序博客网 时间:2024/06/11 02:04

给出一个中括号序列,绘制其层次关系

这种题目没有可对比的地方,就直接粘代码了

//2017年今日头条编程题3import java.util.Scanner;public class Draw {public static void main(String[] args) { drawBrackets();}private static void drawBrackets() {// TODO Auto-generated method stubString str = "";Scanner scanner = new Scanner(System.in);str = scanner.nextLine();scanner.close();char[] cs = str.toCharArray();int[] space = new int[str.length() / 2];//记录每个[的维数int k = 0;int sl = 0;int sr = 0;for (int i = 0; i < cs.length; i++) {if (cs[i] == '[') {sl++;if (sl - sr > k) {k++;for (int j = 0; j < sl; j++) {space[j]++;}} else {space[sl - 1] = space[sl - sr - 1];}} else {sr++;}}int max=0;for(int i=0;i<space.length;i++){if(max<space[i]){max=space[i];}}drawBrackets2(cs, space, 0, -1, 0, 0,max);}/** *  * @param cs * @param space * @param ics cs指针 * @param ispace space指针 * @param isr   ]的个数 * @param x 为一行的起始点 */private static void drawBrackets2(char[] cs, int[] space, int ics, int ispace, int isr, int x,int max) {// TODO Auto-generated method stub//ispace = -1;while (ics < cs.length) {if (cs[ics] == '[') {ispace++;//ispace == 0 || space[ispace] >= space[ispace - 1]if (ics==0||cs[ics-1]==']') {drawLine(space[ispace], '+', x);}if(cs[ics+1]==']'){drawLine2(space[ispace], '|', x);}else{drawLine(max-x, '|', x);}ics++;x++;} else {isr++;ics++;//((ispace + 1) == space.length&&flag==0) ||((ispace + 1) < space.length)&& space[ispace] < space[ispace + 1]if (cs[ics-2]=='[') {System.out.println();}x--;if (cs[ics-2]=='[') {drawLine2(space[ispace], '|', x);}else{drawLine(max-x, '|', x);}//ispace == 0 || space[ispace] >=space[ispace - 1]if (ics==cs.length||((ics<cs.length)&&cs[ics]=='[')) {drawLine(space[ics - 2 * isr], '+', x);}}}}private static void drawLine2(int length, char c, int x) {// TODO Auto-generated method stubfor (int i = 0; i < x; i++) {System.out.print(" ");}System.out.print(c);for(int i=0;i<length-1;i++){System.out.print(" ");}System.out.print(" ");for(int i=0;i<length-1;i++){System.out.print(" ");}System.out.print(c);for (int i = 0; i < x; i++) {System.out.print(" ");}System.out.println();}private static void drawLine(int length, char c, int x) {// TODO Auto-generated method stubfor (int i = 0; i < x; i++) {System.out.print(" ");}System.out.print(c);if (length == 1) {if (c == '+') {System.out.print("-");} else {System.out.print(" ");}}if (length == 2) {if (c == '+') {System.out.print("---");} else {System.out.print("+-+");}}if (length > 2) {if (c == '+') {for (int i = 0; i < length - 1; i++) {System.out.print("-");}System.out.print("-");for (int i = 0; i < length - 1; i++) {System.out.print("-");}} else {System.out.print("+");for (int i = 0; i < length - 2; i++) {System.out.print("-");}System.out.print("-");for (int i = 0; i < length - 2; i++) {System.out.print("-");}System.out.print("+");}}System.out.print(c);for (int i = 0; i < x; i++) {System.out.print(" ");}System.out.println();}}



测试:





0 0