zoukankan      html  css  js  c++  java
  • [LeetCode]224. Basic Calculator(模拟,栈)

    题目链接:https://leetcode.com/problems/basic-calculator/#/description

    题意:计算一个只含有括号、加减、非负数的表达式。

    用一个栈记数,一个栈记符号。

     1 class Solution {
     2 public:
     3     int calculate(string s) {
     4         int n = s.length();
     5         stack<int> st;
     6         stack<char> op;
     7         int ret = 0;
     8         op.push('+');
     9         for(int i = 0; i < n; i++) {
    10             if(isdigit(s[i])) {
    11                 int x = 0;
    12                 while(isdigit(s[i])) x = x * 10 + s[i++] - '0';
    13                 i--;
    14                 char o = op.top(); op.pop();
    15                 if(o == '+') ret += x;
    16                 else ret -= x;
    17             }
    18             else if(s[i] == '+' || s[i] == '-') op.push(s[i]);
    19             else if(s[i] == '(') {
    20                 st.push(ret);
    21                 op.push('+');
    22                 ret = 0;
    23             }
    24             else if(s[i] == ')') {
    25                 char o = op.top(); op.pop();
    26                 if(o == '+') ret += st.top();
    27                 else ret = st.top() - ret;
    28                 st.pop();
    29             }
    30         }
    31         return ret;
    32     }
    33 };
  • 相关阅读:
    大端小端
    浅谈协程
    boost总结之any
    boost总结之variant
    STL总结之functor
    zabbix设置多个收件人
    zabbix设置发送消息的时间
    zabbix利用微信报警
    Windos无法验证文件数组签名
    zabbix基础安装
  • 原文地址:https://www.cnblogs.com/kirai/p/6548456.html
Copyright © 2011-2022 走看看