经典算法一:calculator 224, 227, 772,
1.简单的加减问题,比如:1+2-3=0
1+2-3 可以看作 +1+2-3 , 那么我们可以逐个把这些数字放到stack,最后加起来
class Solution { public int calculate(String s) { Stack<Integer> stack = new Stack(); char op = '+';//开始遍历前默认是正数 int num=0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); if(Character.isDigit(c)){ num=num*10+(c-'0'); } if( i==s.length()-1 || c=='+' || c=='-' ){ if(op=='+') stack.push(num); else stack.push(-num); num=0; op = c; } } int sum = 0; for(int n:stack) sum+=n; return sum; } }
2.如果再加上乘除的问题,比如:1+2-3*4 = -9;
加了乘除后,乘除的优先级要高于加减,因此我们遇到*/的时候,我们先把前面的数组pop出来做完计算再压回stack
class Solution { public int calculate(String s) { Stack<Integer> stack = new Stack(); char op = '+'; int num=0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); if(Character.isDigit(c)){ num=num*10+(c-'0'); } if( i==s.length()-1 || c=='+' || c=='-' || c=='*' || c=='/' ){ if(op=='*') stack.push(stack.pop()*num); else if(op=='/') stack.push(stack.pop()/num); else if(op=='+') stack.push(num); else stack.push(-num); num=0; op = c; } } int sum = 0; for(int n:stack) sum+=n; return sum; } }
3.如果在+-*/基础上增加了括号,比如:5+(3+2-1)*4 = 21
class Solution { int i = 0; public int calculate(String s) { Stack<Integer> stack = new Stack(); char op = '+'; int num=0; while(i<s.length()){ char c = s.charAt(i++); if(c>='0'&&c<='9') num=num*10+(c-'0'); if(c=='(') num = calculate(s);//如果遇到括号,我们把括号里的东西当成一个新的表达式,递归调用计算结果 if( i==s.length() || c=='+' || c=='-' || c=='*' || c=='/' || c==')' ){//坑点:这里不能是else if,因为此处condition也包含上面的情况; 另外)的时候相当于 i==s.length() 已经到达当前表达式的结尾 if(op=='*') stack.push(stack.pop()*num); else if(op=='/') stack.push(stack.pop()/num); else if(op=='+') stack.push(num); else stack.push(-num); num=0; op = c; } if(c==')') break;//坑点:这里别忘了')'的时候要结束当前表达式计算跳出循环 } int sum = 0; for(int n:stack) sum+=n; return sum; } }
自己的最新按部就班做法,没有做任何代码优化,感觉真正面试就要这做:
class Solution { /** 关键点: 1.对于括弧内容,采用递归调用处理 如果是'('进入新一层; 如果是')'跳出当前层 2.对于+-,根据前面op的+-决定当前num的正负 3.注意遍历结束时,最后一个num放入stack */ int ind; public int calculate(String s) { return helper(s); } private int helper(String s) { Stack<Integer> stack = new Stack<>(); int num = 0; char op = '+'; while(ind <= s.length()) { // 遍历结束的话,最后一个元素要放入stack if(ind == s.length()) { stack.push(op == '+' ? num : -num); break; } char c = s.charAt(ind++); // 如果是数字,累加 if(c <= '9' && c >= '0') { num = num * 10 + (c - '0'); } // 如果是操作符,先把先前的加入,再修改操作符 else if(c == '+' || c == '-') { stack.push(op == '+' ? num : -num); op = c; num = 0; } // 如果是(,递归进入新一层处理 else if(c == '(') { int result = helper(s); stack.push(op == '+' ? result : -result); } // 如果是),说明当前层结束,退出循环 else if(c == ')') { stack.push(op == '+' ? num : -num); break; } } int sum = stack.stream().mapToInt(Integer::intValue).sum(); return sum; } } /** 0123456789012345678 (1+(4+5+2)-3)+(6+8) ^ stack:9,14 op:+ stack:6,8 op:+ */
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "3+2*2" Output: 7
Example 2:
Input: s = " 3/2 " Output: 1
Example 3:
Input: s = " 3+5 / 2 " Output: 5
Constraints:
1 <= s.length <= 3 * 105sconsists of integers and operators('+', '-', '*', '/')separated by some number of spaces.srepresents a valid expression.- All the integers in the expression are non-negative integers in the range
[0, 231 - 1]. - The answer is guaranteed to fit in a 32-bit integer.
class Solution { public int calculate(String s) { Stack<Integer> stack = new Stack(); char op = '+'; int num=0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); if(Character.isDigit(c)){ num=num*10+(c-'0'); } if(c=='+'||c=='-'||c=='*'||c=='/'||i==s.length()-1){ //这里有两个坑 1.不要忘了i==s.length()-1这个条件,最后一个数字也是要压栈的 2.条件不能是else if,因为末尾最后一个数字这两个if都满足 if(op=='+') stack.push(num); else if(op=='-') stack.push(-num); else if(op=='*') stack.push(stack.pop()*num); else if(op=='/') stack.push(stack.pop()/num); op = c; num=0; } } int sum = 0; for(int n:stack) sum+=n; return sum; } }
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
The expression string contains only non-negative integers, +, -, *, / operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647]
Do not use the eval built-in library function.
Example 1:
Input:"1 + 1"
Output:2
Explanation:1 + 1 = 2
Example 2:
Input:" 6-4 / 2 "
Output:4
Explanation:4/2=2,6-2=4
/**
* 1.遇到(需要进入下一层循环
* 2.遇到)需要 清算当前数字加入stack,break当前循环
* 3.到达文件结尾需要清算 清算当前数字加入stack
* 4.遇到操作符,需要清算当前数字加入stack,并且覆盖op
*/
public class Solution { private int i=0; public int calculate(String s) { Stack<Integer> stack = new Stack(); int num = 0; char op = '+'; while(i<s.length()){ char c= s.charAt(i++); if(c>='0' && c<='9') num = num*10 + (c-'0'); if(c=='(') num = calculate(s); if(i==s.length() || c=='+' || c=='-' || c=='*' || c=='/' || c==')'){ if(op=='+') stack.push(num); else if(op=='-') stack.push(-num); else if(op=='*') stack.push(stack.pop()*num); else if(op=='/') stack.push(stack.pop()/num); num = 0; op=c; } if(c==')') break; } int sum = 0; for(int n:stack) sum+=n; return sum; } }

浙公网安备 33010602011771号