标签:style blog class code java c
题目:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators
are +
, -
, *
, /
.
Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
算法说明:
使用stack存放数字,若发现运算符,则弹出2个数字进行计数,并将结果压栈。
因为题目未指明输入可能非法,所以没有做严格的错误检查。
时间复杂度O(N),空间复杂度O(N)。
AC代码:
1 class Solution { 2 public: 3 /* 1 for numbers */ 4 int isNumber(string &input, int *number){ 5 int length = input.length(); 6 int tmp = 1; 7 *number = 0; 8 9 for(int i = length - 1; i >= 0; i--){ 10 if(input[i] >= ‘0‘ && input[i] <= ‘9‘){ 11 *number += (input[i] - ‘0‘) * tmp; 12 tmp *= 10; 13 } 14 else if(*number != 0 && input[i] == ‘-‘){ 15 *number *= -1; 16 } 17 else 18 { 19 return 0; 20 } 21 } 22 23 return 1; 24 } 25 26 int evalRPN(vector<string> &tokens) { 27 stack<int> tmpToken; 28 int currNumber = 0; 29 int leftNumber, rightNumber; 30 string tmpString; 31 32 for(int i = 0; i < tokens.size(); i++){ 33 tmpString = tokens[i]; 34 35 if(1 == isNumber(tmpString, &currNumber)){ 36 tmpToken.push(currNumber); 37 }else{ 38 rightNumber = tmpToken.top(); 39 tmpToken.pop(); 40 leftNumber = tmpToken.top(); 41 tmpToken.pop(); 42 switch(tmpString[0]){ 43 case ‘+‘: 44 tmpToken.push(leftNumber + rightNumber); 45 break; 46 case ‘-‘: 47 tmpToken.push(leftNumber - rightNumber); 48 break; 49 case ‘*‘: 50 tmpToken.push(leftNumber * rightNumber); 51 break; 52 case ‘/‘: 53 tmpToken.push(leftNumber / rightNumber); 54 break; 55 default: 56 return -1; 57 break; 58 } 59 } 60 61 } 62 63 return(tmpToken.top()); 64 } 65 };
[LeetCode]Evaluate Reverse Polish Notation,布布扣,bubuko.com
[LeetCode]Evaluate Reverse Polish Notation
标签:style blog class code java c
原文地址:http://www.cnblogs.com/Jason1573/p/3723982.html