思路:将运算符压入栈中,在每个运算符压栈的时候,先和原先栈中的运算符进行优先级的对比,如果优先级高,则正常压栈。如果优先级低,那么先将高优先级运算符出站,然后在进行压栈处理。
package com.example.administrator.androidtest_four;
import java.util.Stack;
/**
* autour : lbing
* date : 2018/7/17 0017 10:39
* className :
* version : 1.0
* description :
*/
public class CalulateChange {
private char[] caculateCharArray = null;
private int length = 0;
private int index = 0;
private Stack<Character> stack = new Stack();
private StringBuilder outPutStr = new StringBuilder();
/**
* 如果有( 就不能出栈
*/
private int leftBrackets = 0;
public CalulateChange(String caculateStr) {
caculateCharArray = caculateStr.toCharArray();
length = caculateCharArray.length;
index = 0;
}
public String start() {
while (index < length) {
StringBuilder dataSource = getDataSource();
startChange(dataSource);
}
//最后将栈中的内容全部的弹出
while (stack.size() > 0) {
outPutStr.append(stack.pop() + " ");
}
return outPutStr.toString();
}
/**
* 将中缀表达式中的数据提取出来
* 方法:将字符串转化成字符数组,然后遍历
*/
public StringBuilder getDataSource() {
StringBuilder tempStr = new StringBuilder();
while (index < length) {
char tempChar = caculateCharArray[index];
if (judgeNoSymbol(tempChar)) {
tempStr.append(tempChar);
} else {
if (tempStr.length() == 0) {
tempStr.append(tempChar);
index++;
}
break;
}
index++;
}
return tempStr;
}
/**
* 如果是符号 先压栈 然后判断下一位运算符 如果即将压栈的运算符不比上一位高,那么就出站运算后压栈
*/
public void startChange(StringBuilder dataSource) {
//有可能是符号或是单位的数字
if (dataSource.length() == 1) {
char tempChar = dataSource.toString().toCharArray()[0];
if (judgeNoSymbol(tempChar)) {
outPutStr.append(dataSource + " ");
} else {
judgeHighPriority(tempChar);
}
//肯定不是符号,因为长度>1
} else {
outPutStr.append(dataSource + " ");
}
}
private boolean judgeNoSymbol(char tempChar) {
if (tempChar == '+'
|| tempChar == '-'
|| tempChar == '*'
|| tempChar == '/'
|| tempChar == '('
|| tempChar == ')'
) {
return false;
} else {
return true;
}
}
private void judgeHighPriority(char oprator) {
if (stack.size() > 0) {
if (oprator == '(') {
leftBrackets++;
stack.push(oprator);
} else if (oprator == ')') {
//如果遇到右括号,就一直弹栈,直到遇到左括号
while (true) {
char peek = stack.peek();
if (peek != '(') {
outPutStr.append(stack.pop() + " ");
} else {
leftBrackets--;
//将左括号弹出栈
stack.pop();
break;
}
}
} else {
if (leftBrackets > 0) {
stack.push(oprator);
} else {
if (oprator != '/' && oprator != '*') {
//判断上一个栈中的运算符是否为高优先级的运算符
while (true) {
char peek = stack.peek();
if (peek == '*' || peek == '/') {
outPutStr.append(stack.pop() + " ");
} else {
break;
}
}
}
stack.push(oprator);
}
}
} else {
stack.push(oprator);
}
}
}
String caculateStr = "11+2*(23-3*4/(23-0))+1";
CalulateChange calulateChange = new CalulateChange(caculateStr);
Log.e("TAG", "后缀表达式====" + calulateChange.start());//11 2 23 3 4 23 0 - / * - * 1 + +