您的位置:首页 > 其它

将表达式转换为逆波兰表达式-LintCode

2017-09-26 20:54 381 查看
给定一个表达式字符串数组,返回该表达式的逆波兰表达式(即去掉括号)。

示例:

对于 [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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: