将表达式转换为逆波兰表达式-LintCode
2017-09-26 20:54
381 查看
给定一个表达式字符串数组,返回该表达式的逆波兰表达式(即去掉括号)。
示例:
对于 [3 - 4 + 5]的表达式(该表达式可表示为[“3”, “-“, “4”, “+”, “5”]),返回 [3 4 - 5 +](该表达式可表示为 [“3”, “4”, “-“, “5”, “+”])。
思想:
对于数字时,加入后缀表达式;
对于运算符:
a. 若为 ‘(‘,入栈;
b. 若为 ‘)’,则依次把栈中的的运算符加入后缀表达式中,直到出现’(‘,从栈中删除’(’ ;
c. 若为 除括号外的其他运算符, 当其优先级高于除’(‘以外的栈顶运算符时,直接入栈。否则从栈顶开始,依次弹出比当前处理的运算符优先级高和优先级相等的运算符,直到一个比它优先级低的或者遇到了一个左括号为止。
当扫描的中缀表达式结束时,栈中的的所有运算符出栈。
示例:
对于 [3 - 4 + 5]的表达式(该表达式可表示为[“3”, “-“, “4”, “+”, “5”]),返回 [3 4 - 5 +](该表达式可表示为 [“3”, “4”, “-“, “5”, “+”])。
思想:
对于数字时,加入后缀表达式;
对于运算符:
a. 若为 ‘(‘,入栈;
b. 若为 ‘)’,则依次把栈中的的运算符加入后缀表达式中,直到出现’(‘,从栈中删除’(’ ;
c. 若为 除括号外的其他运算符, 当其优先级高于除’(‘以外的栈顶运算符时,直接入栈。否则从栈顶开始,依次弹出比当前处理的运算符优先级高和优先级相等的运算符,直到一个比它优先级低的或者遇到了一个左括号为止。
当扫描的中缀表达式结束时,栈中的的所有运算符出栈。
#ifndef C370_H #define C370_H #include<iostream> #include<vector> #include<string> #include<stack> using namespace std; class Solution { public: /* * @param expression: A string array * @return: The Reverse Polish notation of this expression */ vector<string> convertToRPN(vector<string> &expression) { // write your code here vector<string> post; stack<string> sk; for (auto c : expression) { if (c == "(") sk.push(c); else if (c == ")") { while (sk.top() != "(") { post.push_back(sk.top()); sk.pop(); } sk.pop(); } else { if (string("+-*/").find(c) == string::npos) sk.push(c); else { while (!sk.empty() && getPriority(sk.top()) >= getPriority(c)) { post.push_back(sk.top()); sk.pop(); } sk.push(c); } } } while (!sk.empty()) { post.push_back(sk.top()); sk.pop(); } return post; } int getPriority(string s) { if (s == "(") return 0; else if (s == "+" || s == "-") return 1; else if (s == "*" || s == "/") return 2; else return 3; } }; #endif
相关文章推荐
- LintCode 将表达式转换为逆波兰式
- lintcode-将表达式转换为逆波兰表达式-370
- LintCode : 逆波兰表达式求值
- 表达式计算 - 逆波兰式转换及运算示例
- LintCode 424-逆波兰表达式求值
- 将表达式转换为波兰表达式
- 中缀表达式转换为后缀表达式及逆波兰式计算
- [LintCode] Evaluate Reverse Polish Notation 计算逆波兰表达式
- 逆波兰表达式求值-LintCode
- 中缀表达式转换为逆波兰表达式(C++)
- lintcode-逆波兰表达式求值-424
- Java实现-将普通表达式转换成逆波兰表达式并计算
- php简单实现算术表达式转换成逆波兰式,并求解
- lintcode 中等题:Evaluate Reverse Polish notation逆波兰表达式求值
- 逆波兰表达式 转换和计算 C++实现
- c++实现将表达式转换为逆波兰表达式
- 堆栈的应用(2) 中缀算术表达式到后缀(逆波兰记法reverse polish notation)的转换及其计算 C++实现
- 将表达式转换成逆波兰式
- 中序表达式转换为逆波兰表达式
- 【Unity知识搬运】将一个表达式转换为逆波兰式的具体算法思想