Skip to content

Commit 59460dc

Browse files
committed
commit
1 parent 0a701f1 commit 59460dc

File tree

1 file changed

+43
-4
lines changed

1 file changed

+43
-4
lines changed

[0227][Basic Calculator II]/src/Solution.java

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,53 @@
1-
import java.util.Arrays;
21
import java.util.Deque;
3-
import java.util.HashSet;
42
import java.util.LinkedList;
5-
import java.util.Set;
63

74
/**
5+
* https://leetcode.com/problems/basic-calculator-ii/
6+
*
87
* @author: wangjunchao(王俊超)
98
* @time: 2019-07-10 10:54
109
**/
1110
public class Solution {
11+
/**
12+
* <pre>
13+
* Implement a basic calculator to evaluate a simple expression string.
14+
*
15+
* The expression string contains only non-negative integers, +, -, *, / operators
16+
* and empty spaces . The integer division should truncate toward zero.
17+
*
18+
* Example 1:
19+
*
20+
* Input: "3+2*2"
21+
* Output: 7
22+
* Example 2:
23+
*
24+
* Input: " 3/2 "
25+
* Output: 1
26+
* Example 3:
27+
*
28+
* Input: " 3+5 / 2 "
29+
* Output: 5
30+
* Note:
31+
*
32+
* You may assume that the given expression is always valid.
33+
* Do not use the eval built-in library function.
34+
* 思路:
35+
* 遇到加减就入操作数栈和操作符栈,遇到乘除就计算,将计算结果作为新的字符串的第一个值,后面是处理的字符串
36+
* 最后处理所有剩下的加减操作
37+
* 如 1+2+3*4+5+6
38+
* 处理完第一个*号后
39+
* operator: +, +
40+
* operand: 1, 2
41+
* s: 12+5+6
42+
* 整个字符串处理完后
43+
* operator: +, +, +, +
44+
* operand: 1, 2, 12, 5, 6
45+
* 再进行计算
46+
* </pre>
47+
*
48+
* @param s
49+
* @return
50+
*/
1251
public int calculate(String s) {
1352

1453
if (s == null || s.length() < 1) {
@@ -58,7 +97,7 @@ public int calculate(String s) {
5897
// 比如 1*2+3 => 2+3
5998
s = result + s.substring(idx);
6099
idx = 0;
61-
} else if (idx < s.length() && (s.charAt(idx) == '+' || s.charAt(idx) == '-')){
100+
} else if (idx < s.length() && (s.charAt(idx) == '+' || s.charAt(idx) == '-')) {
62101
// 如果是加减
63102
operators.addLast(s.charAt(idx));
64103
idx++;

0 commit comments

Comments
 (0)