LeetCode 逆波兰表达式求值
程序员文章站
2022-07-08 08:54:51
...
LeetCode150.逆波兰表达式求值.
题目
代码
public class Solution
{
public int EvalRPN(string[] tokens)
{
if (tokens.Length == 1)
return Convert.ToInt32(tokens[0]);
double x = 0 / 0.0;
int num = (int)x;
int jnum = num;
Stack<int> stack = new Stack<int>();
stack.Push(Convert.ToInt32(tokens[0]));
stack.Push(Convert.ToInt32(tokens[1]));
for (int i = 2; i < tokens.Length; i++)
{
if (tokens[i] == "*" || tokens[i] == "/" || tokens[i] == "+" || tokens[i] == "-")
{
int p = stack.Peek();
stack.Pop();
int q = stack.Peek();
stack.Pop();
char k = Convert.ToChar(tokens[i]);
switch (k)
{
case '*':
num = q * p;
break;
case '/':
num = q / p;
break;
case '+':
num = q + p;
break;
case '-':
num = q - p;
break;
default:
return jnum;
}
stack.Push(num);
}
else
stack.Push(Convert.ToInt32(tokens[i]));
}
return num;
}
}
前面写的太繁琐了,化简了一下没想到速度飙升。
public class Solution
{
public int EvalRPN(string[] tokens)
{
if (tokens.Length == 1)
return Convert.ToInt32(tokens[0]);
double x = 0 / 0.0;
int jnum = (int)x;
Stack<int> stack = new Stack<int>();
for (int i = 0; i < tokens.Length; i++)
{
if (tokens[i] == "*" || tokens[i] == "/" || tokens[i] == "+" || tokens[i] == "-")
{
int p = stack.Pop();
int q = stack.Pop();
char k = Convert.ToChar(tokens[i]);
switch (k)
{
case '*':
stack.Push(q * p);
break;
case '/':
stack.Push(q / p);
break;
case '+':
stack.Push(q + p);
break;
case '-':
stack.Push(q - p);
break;
default:
return jnum;
}
}
else
stack.Push(Convert.ToInt32(tokens[i]));
}
return stack.Pop();
}
}
上一篇: 我就不值钱吗
下一篇: Spring——使用注解开发