LeetCode: Evaluate Reverse Polish Notation

这题只要理解RPN的原理就不难,用一个stack就行了。为虾米leetcode不提供atoi函数~~只好自己临时写个。注意负数的情况就可以了

 1 class Solution {

 2 public:

 3     int stringtoint(string s) {

 4         int ans = 0;

 5         for (int i = isdigit(s[0])? 0 : 1; i < s.size(); i++) {

 6             ans = ans*10 + s[i] - '0';

 7         }

 8         return isdigit(s[0])? ans : -ans;

 9     }

10     int evalRPN(vector<string> &tokens) {

11         int res = 0;

12         stack<int> S;

13         for (int i = 0; i < tokens.size(); i++) {

14             if (isdigit(tokens[i][0]) || tokens[i].size() > 1 && isdigit(tokens[i][1])) S.push(stringtoint(tokens[i]));

15             else {

16                 int a = S.top();

17                 S.pop();

18                 int b = S.top();

19                 S.pop();

20                 if (tokens[i] == "+") S.push(b+a);

21                 if (tokens[i] == "-") S.push(b-a);

22                 if (tokens[i] == "*") S.push(b*a);

23                 if (tokens[i] == "/") S.push(b/a);

24             }

25         }

26         return S.top();

27     }

28 };

 C#

 1 public class Solution {

 2     public int EvalRPN(string[] tokens) {

 3         int ans = 0;

 4         Stack<int> S = new Stack<int>();

 5         for (int i = 0; i < tokens.Length; i++) {

 6             if (isdigit(tokens[i][0]) || tokens[i].Length > 1 && isdigit(tokens[i][1])) S.Push(stringtoint(tokens[i]));

 7             else {

 8                 int a = S.Peek();

 9                 S.Pop();

10                 int b = S.Peek();

11                 S.Pop();

12                 if (tokens[i] == "+") S.Push(b + a);

13                 if (tokens[i] == "-") S.Push(b - a);

14                 if (tokens[i] == "*") S.Push(b * a);

15                 if (tokens[i] == "/") S.Push(b / a);

16             }

17         }

18         return S.Peek();

19     }

20     public bool isdigit(char c) {

21         return c <= '9' && c >= '0';

22     }

23     public int stringtoint(string s) {

24         int ans = 0;

25         for (int i = isdigit(s[0])? 0 : 1; i < s.Length; i++) {

26             ans = ans * 10 + s[i] - '0';

27         }

28         return isdigit(s[0])? ans : -ans;

29     }

30 }
View Code

 

你可能感兴趣的:(LeetCode)