Scanner/Str(split)2intArray/Arra

2019-06-03  本文已影响0人  小咕咕coco
import java.util.Scanner;
import java.util.Arrays;

public class Bin {
    static int index = 0;       //全局变量,用于遍历before序列
    public static void main(String[] args) {
        int temp;
//对象命名不要和类库冲突
        java.util.Scanner mscanner=new java.util.Scanner(System.in);
//从输入中读取一个int数组
//先读取一行字符串
        String inputstring= mscanner.nextLine();
//切割成子串数组,每个字串是一个代表int的字符串
        String stringArray[]= inputstring.split(";");     //split
        String Before[]=stringArray[0].split(",");
        String Middle[]=stringArray[1].split(",");
//建立数组,string转换为int数组
        int[] before=new int[Before.length];
        int[] middle=new int[Middle.length];
        for (int i=0;i<Before.length;i++){
            before[i]=Integer.parseInt(Before[i]);       //integer.parseInt
            middle[i]=Integer.parseInt(Middle[i]);
        }

//数组可取长度
        int length=middle.length;
        Bin bin = new Bin();
        bin.getAfter(before, middle,length);
    }

    public void getAfter(int[] before, int[] middle,int length){
        int tlength=middle.length;
        if (tlength==0) return;
//index每次递归加1,用以获取before序列中的下一个根字符
        int root = before[index++];
//获取根在中序遍历中出现的位置,以此切割中序遍历的字符串
        int i;
        for (i=0;(i<tlength)&&(middle[i]!=root);i++);
//切分middle字符串,得到left和right两部分
        int[] left =Arrays.copyOfRange(middle,0,i);      //Array.copyOfRange
        int[] right =Arrays.copyOfRange(middle,i+1,tlength);
//递归处理左、右子树
        getAfter(before,left,length);           
        getAfter(before,right,length);  
//输出后序序列
        System.out.print(root);
        if (tlength<length) System.out.print(",");
    }
}

Scanner

上一篇下一篇

猜你喜欢

热点阅读