题解 | #牛牛计算器#
牛牛计算器
https://www.nowcoder.com/practice/192ac31d5e054abcaa10b72d9b01cace
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return int整型 */ public int calculate (String s) { // write code here s = s.replaceAll(" ", ""); StringBuilder str1 = new StringBuilder(); StringBuilder str2 = new StringBuilder(); Stack<Integer> s1 = new Stack<>(); Stack<Character> s2 = new Stack<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch == '+' || ch == '-' || ch == '*' || ch == '/' ) { str1.append(","); str2.append(ch); } else if ( ch == '(' || ch == ')') { str2.append(ch); } else { str1.append(ch); if (str2.length() == 0 || str2.length() != 0 && str2.charAt(str2.length() - 1) != '0'){ str2.append("0"); } } } StringBuilder sb = new StringBuilder(); String[] arr = str1.toString().split(","); for (String str : arr) { if (str != null && str.length() != 0) { sb.append(str + ","); } } arr = sb.substring(0, sb.length() - 1).split(","); int flag = 0; for (int i = 0, j = 0; i < str2.length(); i++) { char ch = str2.charAt(i); if (ch == '*' || ch == '/') { if (str2.charAt(i + 1) == '0') { if (ch == '*') { s1.add(s1.pop() * Integer.valueOf(arr[j])); j++; i++; } else { s1.add(s1.pop() / Integer.valueOf(arr[j])); j++; i++; } } else { s2.add(ch); } } else if (ch == '(') { s2.add(ch); } else if (ch == ')') { while (s2.peek() != '(') { int num1 = s1.pop(); int num2 = s1.pop(); if (s2.pop() == '-') { num1 = 0 - num1; } if (s2.peek() == '-') { num2 = 0 - num2; s2.pop(); s2.add('+'); } s1.add(num1 + num2); } s2.pop(); if (!s2.isEmpty() && s2.peek() == '*') { s2.pop(); int num1 = s1.pop(); int num2 = s1.pop(); s1.add(num1 * num2); } else if (!s2.isEmpty() && s2.peek() == '/') { s2.pop(); int num1 = s1.pop(); int num2 = s1.pop(); s1.add(num2 / num1); } } else if (ch == '+') { s2.add(ch); } else if (ch == '-') { if (i == 0 || (i - 1 >= 0 && str2.charAt(i - 1) != '0' && str2.charAt(i - 1) != ')')) { s1.add(0 - Integer.valueOf(arr[j])); j++; i++; } else { s2.add(ch); } } else { s1.add(Integer.valueOf(arr[j])); j++; } } while (!s2.isEmpty()) { int num1 = s1.pop(); int num2 = s1.pop(); if (s2.pop() == '-') { num1 = 0 - num1; } if (!s2.isEmpty() && s2.peek() == '-') { num2 = 0 - num2; s2.pop(); s2.add('+'); } s1.add(num1 + num2); } return s1.pop(); } }