題目:基本計算器
實現乙個基本的計算器來計算乙個簡單的字串表示式的值。
字串表示式可以包含左括號 ( ,右括號 ),加號 + ,減號 -,非負整數和空格 。
示例1:
輸入: 「1 + 1」示例2:輸出: 2
輸入: 」 2-1 + 2 」示例3:輸出: 3
輸入: 「(1+(4+5+2)-3)+(6+8)」說明:輸出: 23
[c++:]
#include
#include
class solution
int num2 = number_stack.top();
number_stack.pop();
int num1 = number_stack.top();
number_stack.pop();
if(operation_stack.top()=='+')
else
if(operation_stack.top()=='-')
operation_stack.pop();
}int calculate(string s)
switch(state)else
i--;
break;
case number_state:
if(s[i]>='0'&&s[i]<='9')
else
number = 0;
i--;
state = operation_state;
}break;
case operation_state:
if(s[i]=='+'||s[i]=='-')
else
if(s[i]=='(')
else
if(s[i]>='0'&&s[i]<='9')
else
if(s[i]>=')')
break;}}
if(number != 0)
if(number == 0 && number_stack.empty())
return number_stack.top();
}};
leetcode 224 基本計算器
實現乙個基本的計算器來計算乙個簡單的字串表示式的值。字串表示式可以包含左括號 右括號 加號 減號 非負整數和空格 示例 1 輸入 1 1 輸出 2 示例 2 輸入 2 1 2 輸出 3 示例 3 輸入 1 4 5 2 3 6 8 輸出 23 採用雙棧法,設立乙個資料棧和乙個操作符棧,在遍歷字串的過程...
Leetcode 224基本計算器
邏輯先寫第三步再寫第二步,思考時要按照表示式順序先看數字再看右括號正常考慮,時間複雜度o n class solution intcalculate string s else 遇到數字 nums.push n 處理多位數等價寫法 while j s.size isdigit s j j j i c...
leetcode 224 基本計算器
實現乙個基本的計算器來計算乙個簡單的字串表示式的值。字串表示式可以包含左括號 右括號 加號 減號 非負整數和空格 示例 1 輸入 1 1 輸出 2 示例 2 輸入 2 1 2 輸出 3 示例 3 輸入 1 4 5 2 3 6 8 輸出 23 這道題中帶了括號,可以用字尾表示式實現。詳情參見 鏈結1鏈...