支持两位以上的运算,多层嵌套括号或不带括号,栈,递归
package com.monster.stack;
import java.util.Stack;
public class Calculator {
public static void main(String[] args) {
String str = "((3-1+4)*91-8)*2*1";
System.out.println(getChildString(str));
}
public static String getChildString(String str) {
int start = 0;
int end = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '(') {
start = i;
break;
}
}
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) == ')') {
end = i;
break;
}
}
if (start == 0 && end == 0) {
int result = getChildResult(str);
return String.valueOf(result);
}
String childString = str.substring(start + 1, end);
String s = getChildString(childString);
return getChildString(str.substring(0, start) + s + str.substring(end + 1, str.length()));
}
public static int getChildResult(String str) {
int[] numArray = getNumArray(str);
Stack<Integer> numStack = new Stack<>();
Stack<Character> oprStack = new Stack<>();
numStack.push(numArray[0]);
int j = 1;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (isOperate(c)) {
while (!oprStack.empty()) {
if (getPriority(c) <= getPriority(oprStack.peek()))
toCalculator(numStack, oprStack);
else
break;
}
oprStack.push(c);
numStack.push(numArray[j]);
j++;
}
}
while (!oprStack.empty()) {
toCalculator(numStack, oprStack);
}
return numStack.pop();
}
public static void toCalculator(Stack<Integer> numStack, Stack<Character> oprStack) {
Integer num1 = numStack.pop();
Integer num2 = numStack.pop();
int result = getResult(num1, num2, oprStack.pop());
numStack.push(result);
}
public static int getResult(int num1, int num2, char operate) {
int result = 0;
switch (operate) {
case '+':
result = num1 + num2;
break;
case '-':
result = num2 - num1;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num2 / num1;
break;
}
return result;
}
public static int getPriority(char c) {
if (c == '+' || c == '-') {
return 0;
} else {
return 1;
}
}
public static boolean isOperate(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
public static int[] getNumArray(String str) {
String[] split = str.split("\\+|\\-|\\*|\\/");
int[] nums = new int[split.length];
for (int i = 0; i < split.length; i++) {
nums[i] = Integer.parseInt(split[i]);
}
return nums;
}
}