您的位置:首页 > 其它

将表达式转换为波兰表达式

2015-10-26 23:19 281 查看
给定一个表达式字符串数组,返回该表达式的波兰表达式。(即去掉括号)

样例

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