Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
parse-lisp-expression.cpp 1.71 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-11-27 01:40 +08:00 . Update parse-lisp-expression.cpp
// 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;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助