forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
87 lines (69 loc) · 2.14 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/// Source : https://leetcode.com/problems/basic-calculator/description/
/// Author : liuyubobobo
/// Time : 2018-09-03
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
/// Two Stacks
/// Shunting-Yard Algorithms: https://en.wikipedia.org/wiki/Shunting-yard_algorithm
///
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
int calculate(string s) {
vector<int> nums;
vector<char> ops;
for(int i = 0; i < s.size(); ){
if(s[i] == '+' || s[i] == '-' || s[i] == '(')
ops.push_back(s[i++]);
else if(s[i] == ')'){
assert(!ops.empty() && ops.back() == '(');
ops.pop_back();
i ++;
cal(nums, ops);
}
else if(isdigit(s[i])){
int num = s[i] - '0';
int j;
for(j = i + 1; j < s.size() && isdigit(s[j]); j ++)
num = num * 10 + (s[j] - '0');
i = j;
nums.push_back(num);
cal(nums, ops);
}
else
i ++;
// Solution::print_vec(nums);
// Solution::print_vec(ops);
// cout << endl;
}
assert(nums.size() == 1);
return nums.back();
}
private:
void cal(vector<int>& nums, vector<char>& ops){
if(!ops.empty() && (ops.back() == '+' || ops.back() == '-')){
int second = nums.back();
nums.pop_back();
assert(!nums.empty());
int first = nums.back();
nums.pop_back();
nums.push_back(ops.back() == '+' ? (first + second) : (first - second));
ops.pop_back();
}
}
template<typename T>
static void print_vec(const vector<T>& vec){
for(int i = 0; i < vec.size(); i ++)
cout << vec[i] << " ";
cout << endl;
}
};
int main() {
cout << Solution().calculate("1 + 1") << endl; // 2
cout << Solution().calculate(" 2-1 + 2 ") << endl; // 3
cout << Solution().calculate("(1+(4+5+2)-3)+(6+8)") << endl; // 23
return 0;
}