繁体   English   中英

Java - 使用递归的后缀前缀

[英]Java - Prefix to Postfix using recursion

所以我正在学习数据结构课程,我们的任务是为前缀 (-+ABC) 问题制定递归解决方案并将其转换为后缀 (AB+C-) 解决方案。 我觉得我有 70% 的时间......只是错过了那点小东西。

然后返回 outputString 并将其写入 .txt 文件。 我知道这部分工作是由于我过去合作过的实验室。

提供的代码在理论上应该返回 AB+C- 时返回 BCBCABCBCBCABC+ABC

 public static boolean operator(char o) {

    return o == '+' || o == '-' || o == '*' || o == '/' || o == '$';
}

public static String preToPost(String s) {

    char[] c = s.toCharArray();
    // System.out.println(c);
    char ch = c[0];
    //System.out.println(ch);

    char[] cMinusFront = new char[s.length() - 1];

    for (int i = 0, k = 0; i < c.length; i++) {
        if (i == 0) {
            continue;
        }
        cMinusFront[k++] = c[i];

    }

    s = String.valueOf(cMinusFront);
    System.out.println(s);
    String a;
    String b;
    String outputString = null;

    if (s.length() == 1) {
        return outputString;
    }

    if (operator(ch)) {
        a = preToPost(s);

    } else {
        a = s.substring(0, 0);
    }
    if (operator(ch)) {
        b = preToPost(s);
    } else {
        b = s.substring(0, 0);
    }

    outputString = a;
    outputString = outputString.concat(b);
    outputString = outputString.concat(String.valueOf(cMinusFront));

    return outputString;
}

尝试这个。

static boolean isOperator(char ch) {
    return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}

static String preToPost(StringReader input) throws IOException {
    int ch = input.read();
    if (ch == -1)
        return "";
    else if (isOperator((char)ch))
        return preToPost(input) + preToPost(input) + (char)ch;
    else
        return "" + (char)ch;
}

static String preToPost(String input) throws IOException {
    return preToPost(new StringReader(input));
}

public static void main(String[] args) throws IOException {
    System.out.println(preToPost("*-+ABC"));
}

输出:

AB+C-*

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM