给定一个逆波兰表达式,求表达式的值。
数据范围:表达式长度满足
,表达式中仅包含数字和 + ,- , * , / ,其中数字的大小满足
。
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串一维数组 * @return int整型 */ public int evalRPN (String[] tokens) { // write code here Stack<Integer> stack = new Stack<>(); for(int i = 0; i < tokens.length; i++) { if(isDigit(tokens[i])){ stack.push(Integer.parseInt(tokens[i])); }else{ if(tokens[i].equals("+")){ int num2 = stack.pop(); int num1 = stack.pop(); stack.push(num1 + num2); }else if(tokens[i].equals("-")){ int num2 = stack.pop(); int num1 = stack.pop(); stack.push(num1 - num2); }else if(tokens[i].equals("*")){ int num2 = stack.pop(); int num1 = stack.pop(); stack.push(num1 * num2); }else if(tokens[i].equals("/")){ int num2 = stack.pop(); int num1 = stack.pop(); stack.push(num1 / num2); } } } return stack.pop(); } private boolean isDigit(String s) { try{ Integer.parseInt(s); return true; }catch(Exception e) { return false; } } }
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串vector * @return int整型 */ int evalRPN(vector<string>& tokens) { // write code here // 时间复杂度O(N),空间复杂度O(N) stack<string> stk; int n1, n2, res; for (string &s : tokens) { if (s == "+" || s == "-" || s == "*" || s == "/") { n2 = stoi(stk.top()); stk.pop(); n1 = stoi(stk.top()); stk.pop(); if (s == "+") res = n1 + n2; else if (s == "-") res = n1 - n2; else if (s == "*") res = n1 * n2; else res = n1 / n2; stk.push(to_string(res)); } else stk.push(s); } return stoi(stk.top()); } };
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param tokens string字符串一维数组 # @return int整型 # class Solution: def evalRPN(self , tokens: List[str]) -> int: # write code here """ 逆波兰表达式 1. 维护一个栈,栈中只保存数值 -> stack = [] 2. 如果遇到数,存到栈中 3. 如果遇到运算符,从stack中取出两个元素进行相应的计算并存储回栈中 """ stack = [] for elem in tokens: # 如果是运算符 if elem in "+-*/": # 从栈中取出两个元素 first = stack.pop() second = stack.pop() # 根据运算符进行对应计算 if elem == "+": stack.append(second + first) elif elem == "-": stack.append(second - first) elif elem == "*": stack.append(second * first) else: stack.append(int(second / first)) # 如果数 else: stack.append(int(elem)) # 最后取出栈的元素 return stack.pop()
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串vector * @return int整型 */ int evalRPN(vector<string>& tokens) { // write code here stack<int> sta; for(int i=0;i<tokens.size();i++) { if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/") { int num=sta.top();sta.pop();int num1=sta.top();sta.pop(); if(tokens[i]=="+"){sta.push(num+num1);} if(tokens[i]=="-"){sta.push(num1-num);} if(tokens[i]=="*"){sta.push(num*num1);} if(tokens[i]=="/"){sta.push(num1/num);} } else {sta.push(stoi(tokens[i]));} } return sta.top(); } };
class Solution: def evalRPN(self , tokens: List[str]) -> int: # write code here ls = [] for i in range(len(tokens)): if tokens[i] in ["+","-","*","/"]: l1 = ls.pop() l2 = ls.pop() res = str(int(eval(l2 + tokens[i] + l1))) ls.append(res) else: ls.append(tokens[i]) return int(ls[-1])
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param tokens string字符串一维数组 * @return int整型 */ public int evalRPN (String[] tokens) { Stack<Integer> stack = new Stack<>(); for (String token : tokens) { if (token.equals("+")) { int b = stack.pop(); int a = stack.pop(); stack.push(a + b); } else if (token.equals("-")) { int b = stack.pop(); int a = stack.pop(); stack.push(a - b); } else if (token.equals("*")) { int b = stack.pop(); int a = stack.pop(); stack.push(a * b); } else if (token.equals("/")) { int b = stack.pop(); int a = stack.pop(); stack.push(a / b); } else { stack.push(Integer.parseInt(token)); } } return stack.pop(); } }
#include<iostream> #include<string> #include<vector> #include<stack> using namespace std; int NumberTransform(string& str) { int size = str.size(); if (str[0] == '-') { //负数 if (size - 1 == 3) { //三位数 return -((str[1] - '0') * 100 + ((str[2] - '0') * 10) + (str[3] - '0')); } else if (size - 1 == 2) { //两位数 return -((str[1] - '0') * 10 + (str[2] - '0')); } else { //一位数 return -(str[1] - '0'); } } else { //正数 if (size == 3) { //三位数 return (str[0] - '0') * 100 + (str[1] - '0') * 10 + (str[2] - '0'); } else if (size == 2) { //两位数 return (str[0] - '0') * 10 + (str[1] - '0'); } else { //一位数 return str[0] - '0'; } } } int Calculation(stack<int>& st, string& str) {//计算 int a = 0; int b = 0; a = st.top(); st.pop(); b = st.top(); st.pop(); if (str == "+") return b + a; else if (str == "-") return b - a; else if (str == "*") return b * a; else return b / a; } class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串vector * @return int整型 */ int evalRPN(vector<string>& tokens) { // write code here int size = tokens.size(); //字符串的个数 //辅助栈 stack<int> st;//存为数字的字符对应的10进制数 string str;//临时接收字符串 int i = 0; //访问vector的下标 for (i = 0; i < size; i++) {//容器的遍历,这里最好使用迭代器 //但这样的遍历也是可以的 str = tokens[i]; if (str == "+" || str == "-" || str == "*" || str == "/") { //取数计算 int result = Calculation(st, str); st.push(result); } else { //把字符串转换为数字入栈 int temp = NumberTransform(str); //这个函数仅仅能针对这个题, //其实这个字符串转化为数的功能是有专门额函数的 //整数 stoi(字符串) 比如 stoi("123") 它的返回值就是 123 // stoi("-123") 它的返回值就是 -123 这是简单的应用 st.push(temp); } } return st.top(); } };
public int evalRPN (String[] tokens) { ArrayDeque<Integer> stack = new ArrayDeque<>(); for (String t : tokens) { if (t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/")) { int a = stack.pop(), b = stack.pop(); if (t.equals("+")) stack.push(b+a); else if (t.equals("-")) stack.push(b-a); else if (t.equals("*")) stack.push(b*a); else stack.push(b/a); } else { stack.push(Integer.parseInt(t)); } } return stack.peek(); }
using System; using System.Collections.Generic; class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串一维数组 * @return int整型 */ public int evalRPN (List<string> tokens) { //一个字符,直接输出 if (tokens.Count == 1) return int.Parse(tokens[0]); //三个字符,直接算 if (tokens.Count == 3) return operiation(int.Parse(tokens[0]), int.Parse(tokens[1]), tokens[2]); Stack<string> stack = new Stack<string>(); int number; foreach (var token in tokens) { if (!int.TryParse(token, out number)) { int y = int.Parse(stack.Pop()); int x = int.Parse(stack.Pop()); int result = operiation(x, y, token); stack.Push(result.ToString()); } else stack.Push(token); } return int.Parse(stack.Pop()); } public int operiation(int x, int y, string oper) { switch (oper) { case "+" : x = x + y; break; case "-" : x = x - y ; break; case "*" : x = x * y; break; case "/" : x = x / y ; break; default: break; } return x; } }
#include <iostream> #include <vector> #include <stack> #include <string> using namespace std; class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串vector * @return int整型 */ //匹配问题,使用栈进行模拟 stack <int> nums;//运算数字栈 bool nonum(string c) { if (c == "+" || c == "-" || c == "*" || c == "/") { return true; } else { return false; } } int compute(int a, int b, string c) { if (c == "+") { return a + b; } else if (c == "-") { return a - b; } else if (c == "*") { return a * b; } else { if (b == 0) { return -1; } return a / b; } } // 手动实现字符串转整数功能 int my_stoi(const string& str) { int result = 0; int sign = 1; size_t i = 0; if (str[0] == '-') { sign = -1; i = 1; } for (; i < str.length(); ++i) { result = result * 10 + (str[i] - '0'); } return result * sign; } int evalRPN(vector<string>& tokens) { int temp1, temp2; string c; for (int i = 0; i < tokens.size(); i++) { c = tokens[i]; if (!nonum(c)) { //如果是数字,入栈 nums.push(my_stoi(c)); } else { if (nums.size() < 2) { return -1; } else { temp2 = nums.top(); nums.pop(); temp1 = nums.top(); nums.pop(); nums.push(compute(temp1, temp2, c)); } } } return nums.top(); // write code here } };能在C++98运行的算法
import java.util.*; /** * NC216 逆波兰表达式求值 * @author d3y1 */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串一维数组 * @return int整型 */ public int evalRPN (String[] tokens) { Stack<Integer> stack = new Stack<>(); int leftVal,rightVal; for(String token: tokens){ switch(token){ case "+": rightVal=stack.pop();leftVal=stack.pop();stack.push(leftVal+rightVal); break; case "-": rightVal=stack.pop();leftVal=stack.pop();stack.push(leftVal-rightVal); break; case "*": rightVal=stack.pop();leftVal=stack.pop();stack.push(leftVal*rightVal); break; case "/": rightVal=stack.pop();leftVal=stack.pop();stack.push(leftVal/rightVal); break; default: stack.push(Integer.parseInt(token)); break; } } // + - * / // String regex = "[+\\-*/]"; // for(String token: tokens){ // if(token.matches(regex)){ // rightVal = stack.pop(); // leftVal = stack.pop(); // switch(token){ // case "+": stack.push(leftVal+rightVal); break; // case "-": stack.push(leftVal-rightVal); break; // case "*": stack.push(leftVal*rightVal); break; // case "/": stack.push(leftVal/rightVal); break; // default: break; // } // }else{ // stack.push(Integer.parseInt(token)); // } // } return stack.pop(); } }
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串一维数组 * @param tokensLen int tokens数组长度 * @return int整型 */ #include <stdio.h> int evalRPN(char** tokens, int tokensLen ) { // write code here int n[10000]={0},top=-1,i,j,k,l,a,b,m=0; for(i=0;i<tokensLen;i++){ if(**(tokens+i)=='+'){ b=n[top--]; a=n[top--]; n[++top]=(a+b); continue; } if((**(tokens+i)=='-')&&*(*(tokens+i)+1)=='\0'){ b=n[top--]; a=n[top--]; n[++top]=(a-b); continue; } if(**(tokens+i)=='*'){ b=n[top--]; a=n[top--]; n[++top]=(a*b); continue; } if(**(tokens+i)=='/'){ b=n[top--]; a=n[top--]; n[++top]=(a/b); continue; } if(**(tokens+i)>='0'&&**(tokens+i)<='9'){ //k=sizeof(*(tokens+i))/; m=0,j=0; while(*(*(tokens+i)+j)!='\0') { m=m*10+(*(*(tokens+i)+j)-'0'); j++; } n[++top]=m; continue; } if(**(tokens+i)=='-'&&*(*(tokens+i)+1)!='\0'){ //k=sizeof(*(tokens+i))/; m=0,j=1; while(*(*(tokens+i)+j)!='\0') { m=m*10+(*(*(tokens+i)+j)-'0'); j++; } n[++top]=0-m; continue; } printf("%c",**(tokens+i)); } return n[top]; }
static int compute(String[] tokens) { int[] params = new int[2]; for (int i = 0; i < tokens.length; i++) { switch (tokens[i]) { case "+": params[0] = params[0] + params[1]; break; case "-": params[0] = params[0] - params[1]; break; case "*": params[0] = params[0] * params[1]; break; case "/": params[0] = params[0] / params[1]; break; default: //计算数据存放的index位置 params[i & 1] = Integer.parseInt(tokens[i]); break; } } return params[0]; }