這個的思路賊拉簡單
本次只對純粹使用堆棧來解決該問題給出解答
首先給出僞代碼
input(expr)
map<K,V> Map
Map.put('(',-1)
Map.put('[+,-]',1)
Map.put('[*,/]',2)
#建立字典映射
for i in expr:
#遍歷expr中的個體元素
if i is number:
string+=number
#如果是數據則直接輸出
else
if i is ):
#如果是右括號,那麼就要開始把符號棧中的元素彈出,直到當前的優先級比我低
#簡單來說如果只有+-*/四則運算,如果是*號那麼要把* /在符號棧中彈出來,讓他們先去運算
#如果是+-,則彈出+-*/
while(stack.peek()!='('):
string+=stack.pop()
stack.pop()#扔掉'('
stack.push(i)
else:
while(Map[i]>stack.peek()):
string+=stack.pop()
if stack is empty or stack.peek() is '(':
break
Stack.push(i)
#如果棧還沒有空,繼續
while(stack not empty):
string+=stack.pop()
return string
再給出java版本的實現
package day05;
import java.util.HashMap;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author 海綿寶寶
* @create 2019- 10- 29 19:45
**/
public class Problems {
public static boolean isNumber(char c){
String ss = ""+c;
Pattern pattern=Pattern.compile("[0-9]*");
return pattern.matcher(ss).matches();
}
//中綴表達式轉後綴表達式
public static String MiddleToBack(String args){
HashMap<Character, Integer>map = new HashMap<Character, Integer>();
map.put('(', -1);
map.put(')', 100);
map.put('+', 0);
map.put('-', 0);
map.put('*', 1);
map.put('/', 1);
char[] expr =args.toCharArray();
Stack<Character>OpStack = new Stack<Character>();
String string="";
String backString="";
for (int i = 0; i < expr.length; i++) {
if (isNumber(expr[i])){
while (isNumber(expr[i])){
string+=expr[i];
i++;
if (i==expr.length)break;
}
if (i==expr.length);
else i--;
//
backString+=string+" ";
string="";
}
else{
if (expr[i]==' ')continue;
else{
if (OpStack.isEmpty()){
OpStack.push(expr[i]);
}
else{
if (expr[i]=='('){
OpStack.push(expr[i]);
}
else if(expr[i]==')'){
while (OpStack.isEmpty() == false&&OpStack.peek()!='('){
backString+=OpStack.pop()+" ";
}
if (!OpStack.isEmpty())
OpStack.pop();
}
else {
if (OpStack.isEmpty()){
OpStack.push(expr[i]);
}
while (map.get(expr[i])<map.get(OpStack.peek())){
if (OpStack.peek()=='(')break;
backString+=OpStack.pop()+" ";
if (OpStack.isEmpty())break;
}
OpStack.push(expr[i]);
}
}
}
}
}
while (!OpStack.isEmpty()){
backString+=OpStack.pop()+ " ";
}
return backString;
}
public static void main(String[] args) {
String expr= "(5+6)+7";
System.out.println(MiddleToBack(expr));
}
}
最後附上處理後綴表達的一半方法
public static int SolveTheProblem(String expr){
Stack<Integer>NumStack = new Stack<Integer>();
String[]exp = expr.split(" ");
for (String i :
exp) {
if (isNumber(i)){
NumStack.push((Integer.parseInt(i)));
}
else{
int second = NumStack.pop();
int first=NumStack.pop();
int result = 0;
switch (i){
case "+":result=second+first;
break;
case "-":result=first-second;
break;
case "*":result=first*second;
break;
case "/":result=first/second;
break;
default:
System.out.println("error,uninvalib simble");
}
NumStack.push(result);
}
}
return NumStack.peek();
}