将表达式转换为波兰表达式
2015-10-26 23:19
281 查看
给定一个表达式字符串数组,返回该表达式的波兰表达式。(即去掉括号)
样例
对于 [(5 − 6) * 7] 的表达式(该表达式可表示为
样例
对于 [(5 − 6) * 7] 的表达式(该表达式可表示为
["(", "5", "−", "6", ")", "*", "7"]),其对应的波兰表达式为 [* - 5 6 7](其返回的数值为
["*", "−", "5", "6", "7"])。
class Solution { public: /** * @param expression: A string array * @return: The Polish notation of this expression */ vector<string> convertToPN(vector<string> &expression) { // write your code here int n = expression.size(); vector<string> result; stack<string> operators; stack<string> buf; for (int i = n-1; i >= 0; i--) { if (expression[i].length() == 1 && isOperator(expression[i])) { if (operators.empty()) { operators.push(expression[i]); } else if (expression[i] == ")") { operators.push(expression[i]); } else if (expression[i] == "(") { while (operators.top() != ")") { buf.push(operators.top()); operators.pop(); } operators.pop(); } else { if (compare(expression[i], operators.top())) { operators.push(expression[i]); } else { while (!operators.empty() && !compare(expression[i], operators.top())) { buf.push(operators.top()); operators.pop(); } operators.push(expression[i]); } } } else { buf.push(expression[i]); } } while (!operators.empty()) { buf.push(operators.top()); operators.pop(); } while (!buf.empty()) { result.push_back(buf.top()); buf.pop(); } return result; } private: bool compare(string &a, string &b) { if (b == ")") { return true; } if (a == "*" || a == "/") { return true; } else if (b == "+" || b == "-") { return true; } return false; } bool isOperator(string &a) { if (a == "+" || a == "-" || a == "*" || a == "/" || a == "(" || a == ")") { return true; } return false; } };
相关文章推荐
- Popover 初探
- CLR via C# 读书笔记---常量、字段、方法和参数
- 国家以及国家语言的json数据格式,提供给网友参考。
- 排序算法(一)------直接插入排序和希尔排序
- opencv 两幅图像融合
- 动态为TextView设置drawableRight
- IPA的4种打包方式
- 【Leetcode】Nim Game
- Ajax
- 几种ESB(企业服务总线)介绍
- Opencv 鼠标事件GUI
- [Leetcode]Path Sum II
- Windows 10还原为Windows 8/7
- 静态
- 【2015/10/24】C学习日志_Day 9 关键字
- 文章标题
- C++Primer笔记一
- jackson学习----解析豆瓣的图书信息
- 【黑马程序员】成为一匹黑色战马,驰骋于技术的荒野之中
- android群英传读书笔记---自定义ViewGroup