Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594

[LeetCode]Evaluate Reverse Polish Notation-2013.12.27

Posted on 2014-01-11 02:51 Uriel 阅读(132) 评论(0)  编辑 收藏 引用 所属分类: LeetCode
一天遇到两次一样的题简直...要是能在之前一天能做一下这题多好,就不至于当时题目问了几遍才明白...
给出逆波兰式,求算式的值,模拟栈,乘除的时候注意出栈顺序!和算式的操作数顺序相反!下午就死在这上面了...

 1 class Solution {
 2 public:
 3     int evalRPN(vector<string> &tokens) {
 4         int stk[1010], k = 0;
 5         for(int i = 0; i < tokens.size(); ++i) {
 6             if(tokens[i] == "+") {
 7                 int a = stk[k - 1], b = stk[k - 2];
 8                 k -= 2;
 9                 stk[k++] = a + b;
10             }
11             else if(tokens[i] == "-") {
12                 int a = stk[k - 1], b = stk[k - 2];
13                 k -= 2;
14                 stk[k++] = b - a;
15             }
16             else if(tokens[i] == "*") {
17                 int a = stk[k - 1], b = stk[k - 2];
18                 k -= 2;
19                 stk[k++] = b * a;
20             }
21             else if(tokens[i] == "/") {
22                 int a = stk[k - 1], b = stk[k - 2];
23                 k -= 2;
24                 stk[k++] = b / a;
25             }
26             else {
27                 stk[k++] = atoi(tokens[i].c_str());
28             }
29         }
30         return stk[0];
31     }
32 };

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理