zoukankan      html  css  js  c++  java
  • leetcode 772 基本计算器III(包含+-*/ 以及括号) 核心在于递归

    现基本计算器以计算简单表达式字符串。

    表达式字符串可以包含左括号(和右括号)、加号+或减号、非负整数和空格。

    表达式字符串只包含非负整数、+、-、*、/运算符、左括号和空格。整数除法应该截断为零。

    您可以假定给定的表达式总是有效的。所有中间结果将在范围内[-2147483648,2147483647]

    "1 + 1" = 2
    " 6-4 / 2 " = 4
    "2*(5+5*2)/3+(6/2+8)" = 21
    "(2+6* 3+5- (3*14/7+2)*5)+3"=-12

    class Solution {
    public:
        int FindClosing(string s,int i){
            int level = 0,k=0;
            for(k=i;k<s.size()-1;k++){
                if(s[k] == '(') level++;
                if(s[k] == ')') {
                    if(--level == 0) return k;
                }
            }
            return k;
        }
        //带括号的话,用递归,更难一些(找到对应层级的括号并同时删除)
        int calculate(string s) {
            //利用栈: 3+5/2*3转化为 +3 +5 /2 *3
            stack<int> nums;
            int n = s.size();
            int num = 0,res =0,pre=0;
            char sign = '+';
            for(int i=0;i<n;){
                //if(isspace(s[i])) continue; 忽略不用管空格
                if(isdigit(s[i])){
                    num = num*10+(s[i]-'0');
                }
                if(s[i] == '('){
                    //s的子串,找),剔除()
                    int j = FindClosing(s,i);
                    num = calculate(s.substr(i+1,j));
                    i+=j;
                }
                if(!isspace(s[i]) && !isdigit(s[i]) || i == n-1){
                    switch (sign){
                    case '+':
                        nums.push(num);
                        break;
                    case '-':
                        nums.push(-num);
                        break;
                    case '*':
                        pre=nums.top();
                        nums.pop();
                        nums.push(pre*num);
                        break;
                    case '/':
                        pre=nums.top();
                        nums.pop();
                        nums.push(pre/num);
                        break;
                    }
                    sign = s[i];
                    num = 0;
                }
                i++;
            }
            while(!nums.empty()){
                res += nums.top();
                nums.pop();
            }
            return res;
        }
        
    };
  • 相关阅读:
    HTTP断点续传 规格严格
    Java Shutdown 规格严格
    linux 命令源码 规格严格
    JTable调整列宽 规格严格
    linux 多CPU 规格严格
    Hello can not find git path 规格严格
    Kill 规格严格
    拜拜牛人 规格严格
    Swing 规格严格
    Debugging hangs in JVM (on AIX but methodology applicable to other platforms) 规格严格
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/14076223.html
Copyright © 2011-2022 走看看