【问题标题】:Prefix To Postfix Java前缀到后缀 Java
【发布时间】:2022-01-23 04:13:09
【问题描述】:

我需要一些关于后缀代码前缀的帮助。当我通过 GUI 从表达式“* 2 + 2 - + 12 9 2”生成动作时,它返回 2*。它应该返回“2 2 12 9 + 2 -+*”。我不断更改代码,并不断得到相同的结果。如有任何指导,我将不胜感激。

import java.util.*; 

public class Postfix{ 
      
    static String prePostfix(String p){ 
      
        Stack<String> stack = new Stack<String>(); 
      
        int l = p.length(); 
      
        for(int i = l-1; i >= 0; i--){ 
            if(isOperator(p.charAt(i))){ 
      
                String stack1 = stack.peek(); 
                stack.pop();
                String stack2 = stack.peek(); 
                stack.pop(); 
      
                String temp = stack1 + stack2 + p.charAt(i); 
      
                stack.push(temp); 
            } 
      
            else{ 
                stack.push(p.charAt(i) + ""); 
            } 
        } 
      
        return stack.peek(); 
    } 
    
    static boolean isOperator(char x){ 
        switch (x){ 
            case '+':
            case '-': 
            case '/': 
            case '*':
            case '^':
                return true; 
        } 
        return false; 
    } 
}

【问题讨论】:

    标签: java algorithm data-structures stack postfix-mta


    【解决方案1】:

    您的问题是您没有考虑表达式中的分隔符,即每个子表达式之间的空格。

    我建议您不要使用分隔符处理原始字符串, 只需将您的字符串拆分为参数并处理该数组,然后使用您喜欢的分隔符加入它们。

    不管怎样,这里是固定的代码:

    import java.util.*; 
    
    public class Postfix{ 
      
    static String prePostfix(String p){ 
      
        Stack<String> stack = new Stack<String>(); 
        String[] arrOfStr = p.split(" ");
        int l = arrOfStr.length; 
        for(int i = l-1; i >= 0; i--){ 
            if(isOperator(arrOfStr[i].charAt(0))){ 
      
                String stack1 = stack.peek(); 
                stack.pop();
                String stack2 = stack.peek(); 
                stack.pop(); 
      
                String temp = stack1 + " " + stack2 + " " + arrOfStr[i]; 
      
                stack.push(temp); 
            } 
            else{ 
                stack.push(arrOfStr[i]); 
            } 
        } 
      
        return stack.peek(); 
    } 
    
    static boolean isOperator(char x){ 
        switch (x){ 
            case '+':
            case '-': 
            case '/': 
            case '*':
            case '^':
                return true; 
        } 
        return false; 
    } 
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 2017-01-23
      相关资源
      最近更新 更多