题解 | #中缀表达式转后缀表达式#
中缀表达式转后缀表达式
http://www.nowcoder.com/practice/4e7267b55fdf430d9403aa12206572b3
import java.util.Scanner; import java.util.Stack; import java.util.HashMap; import java.lang.String; public class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); char[] array=sc.nextLine().toCharArray(); StringBuilder builder=new StringBuilder(); Stack<Character> s=new Stack<Character>(); HashMap<Character,Integer> map=new HashMap<>(); map.put('+',1); map.put('-',1); map.put('*',2); map.put('/',2); for(char c:array) { if(Character.isLetter(c)) { builder.append(c); }else{ while(!s.isEmpty()&&map.get(c)<=map.get(s.peek()))//'+','-','*','/'比较 { builder.append(s.pop()); } s.push(c); } } while (!s.empty()) { builder.append(s.pop()); } System.out.println(builder.toString()); } }