|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| - |
4 | 3 | import java.util.ArrayDeque;
|
5 | 4 | import java.util.Deque;
|
6 | 5 |
|
|
21 | 20 | */
|
22 | 21 | public class _227 {
|
23 | 22 |
|
24 |
| - /**Credit: https://discuss.leetcode.com/topic/16935/share-my-java-solution*/ |
25 |
| - public int calculate(String s) { |
26 |
| - if (s == null || s.length() == 0) { |
27 |
| - return 0; |
28 |
| - } |
29 |
| - int len = s.length(); |
30 |
| - Deque<Integer> stack = new ArrayDeque<>(); |
31 |
| - int num = 0; |
32 |
| - char sign = '+'; |
33 |
| - for (int i = 0; i < len; i++) { |
34 |
| - if (Character.isDigit(s.charAt(i))) { |
35 |
| - num = num * 10 + s.charAt(i) - '0'; |
| 23 | + public static class Solution1 { |
| 24 | + public int calculate(String s) { |
| 25 | + if (s == null || s.length() == 0) { |
| 26 | + return 0; |
36 | 27 | }
|
37 |
| - if ((!Character.isDigit(s.charAt(i))) && ' ' != s.charAt(i) || i == len - 1) { |
38 |
| - if (sign == '+') { |
39 |
| - stack.addLast(num); |
40 |
| - } else if (sign == '-') { |
41 |
| - stack.addLast(-num); |
42 |
| - } else if (sign == '/') { |
43 |
| - stack.addLast(stack.pollLast() / num); |
44 |
| - } else if (sign == '*') { |
45 |
| - stack.addLast(stack.pollLast() * num); |
| 28 | + int len = s.length(); |
| 29 | + Deque<Integer> stack = new ArrayDeque<>(); |
| 30 | + int num = 0; |
| 31 | + char sign = '+'; |
| 32 | + for (int i = 0; i < len; i++) { |
| 33 | + if (Character.isDigit(s.charAt(i))) { |
| 34 | + num = num * 10 + s.charAt(i) - '0'; |
| 35 | + } |
| 36 | + if ((!Character.isDigit(s.charAt(i))) && ' ' != s.charAt(i) || i == len - 1) { |
| 37 | + if (sign == '+') { |
| 38 | + stack.addLast(num); |
| 39 | + } else if (sign == '-') { |
| 40 | + stack.addLast(-num); |
| 41 | + } else if (sign == '/') { |
| 42 | + stack.addLast(stack.pollLast() / num); |
| 43 | + } else if (sign == '*') { |
| 44 | + stack.addLast(stack.pollLast() * num); |
| 45 | + } |
| 46 | + sign = s.charAt(i); |
| 47 | + num = 0; |
46 | 48 | }
|
47 |
| - sign = s.charAt(i); |
48 |
| - num = 0; |
49 | 49 | }
|
| 50 | + int result = 0; |
| 51 | + while (!stack.isEmpty()) { |
| 52 | + result += stack.poll(); |
| 53 | + } |
| 54 | + return result; |
50 | 55 | }
|
51 |
| - int result = 0; |
52 |
| - while (!stack.isEmpty()) { |
53 |
| - result += stack.poll(); |
54 |
| - } |
55 |
| - return result; |
56 | 56 | }
|
57 |
| - |
58 | 57 | }
|
0 commit comments