1 Star 0 Fork 1

陈鹏/leecode with labuladong

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
241.为运算表达式设计优先级.cpp 1.00 KB
Copy Edit Raw Blame History
陈鹏 authored 2022-07-26 21:28 . 面试高频题(1)
/*
* @lc app=leetcode.cn id=241 lang=cpp
*
* [241] 为运算表达式设计优先级
*/
// @lc code=start
class Solution {
public:
unordered_map<string, vector<int>> memo;
vector<int> diffWaysToCompute(string expression) {
if (memo.find(expression) != memo.end()) {
return memo[expression];
}
if (expression.find_first_of("+-*") == expression.npos) {
return {stoi(expression)};
}
vector<int> ans;
int pos = 0;
while ((pos = expression.find_first_of("+-*", pos + 1)) != expression.npos) {
vector<int> left = diffWaysToCompute(expression.substr(0, pos)), right = diffWaysToCompute(expression.substr(pos + 1));
for (int l : left) {
for (int r : right) {
ans.emplace_back(expression[pos] == '+' ? l + r : expression[pos] == '-' ? l - r : l * r);
}
}
}
memo[expression] = ans;
return memo[expression];
}
};
// @lc code=end
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Chan1998/leecode-with-labuladong.git
git@gitee.com:Chan1998/leecode-with-labuladong.git
Chan1998
leecode-with-labuladong
leecode with labuladong
master

Search