LeetCode 224: Basic Calculator Solution
Master LeetCode problem 224 (Basic Calculator), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we will use a stack to keep track of the operands and operators as we process the input expression. We will iterate through the string character by character and handle different cases such as digits, operators, and parentheses. By maintaining a running total and a sign value, we can calculate the result of the expression.
- Initialize a stack to store the operands and a variable
resultto store the final result. - Initialize
signas 1 to represent the positive sign. - Iterate through each character of the input string
s. - If the character is a digit, update the
numvariable. - If the character is an operator (+ or -), update the
resultandsignaccordingly. - If the character is an opening parenthesis, push the current
resultandsignonto the stack and reset them. - If the character is a closing parenthesis, calculate the result within the current parentheses and update the
resultandsignvalues. - Finally, return the calculated
result.
Time Complexity: O(n), where n is the length of the input string s.
Space Complexity: O(n), where n is the length of the input string s.
Solution Code
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
int result = 0;
int num = 0;
int sign = 1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '+') {
result += sign * num;
num = 0;
sign = 1;
} else if (c == '-') {
result += sign * num;
num = 0;
sign = -1;
} else if (c == '(') {
stack.push(result);
stack.push(sign);
result = 0;
sign = 1;
} else if (c == ')') {
result += sign * num;
num = 0;
result *= stack.pop(); // pop the sign
result += stack.pop(); // add back the result outside the parentheses
}
}
if (num != 0) {
result += sign * num;
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 224 (Basic Calculator)?
This page provides optimized solutions for LeetCode problem 224 (Basic Calculator) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 224 (Basic Calculator)?
The time complexity for LeetCode 224 (Basic Calculator) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 224 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 224 in Java, C++, or Python.