forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse-lisp-expression.cpp
50 lines (47 loc) · 1.71 KB
/
parse-lisp-expression.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
// Time: O(n^2)
// Space: O(n^2)
class Solution {
public:
int evaluate(string expression) {
vector<string> tokens{""};
unordered_map<string, string> lookup;
vector<pair<vector<string>, unordered_map<string, string>>> stk;
for (const auto& c : expression) {
if (c == '(') {
if (tokens[0] == "let") {
evaluate(tokens, &lookup);
}
stk.emplace_back(move(tokens), lookup);
tokens = {""};
} else if (c == ' ') {
tokens.emplace_back();
} else if (c == ')') {
const auto& val = evaluate(tokens, &lookup);
tie(tokens, lookup) = move(stk.back());
stk.pop_back();
tokens.back() += val;
} else {
tokens.back().push_back(c);
}
}
return stoi(tokens[0]);
}
private:
string evaluate(const vector<string>& tokens, unordered_map<string, string>* lookup) {
static const unordered_set<string> operators{"add", "mult"};
if (operators.count(tokens[0])) {
const auto& a = stoi(getval(*lookup, tokens[1]));
const auto& b = stoi(getval(*lookup, tokens[2]));
return to_string(tokens[0] == "add" ? a + b : a * b);
}
for (int i = 1; i < tokens.size() - 1; i += 2) {
if (!tokens[i + 1].empty()) {
(*lookup)[tokens[i]] = getval(*lookup, tokens[i + 1]);
}
}
return getval(*lookup, tokens.back());
}
string getval(const unordered_map<string, string>& lookup, const string& x) {
return lookup.count(x) ? lookup.at(x) : x;
}
};