id int64 1 3.58k | problem_description stringlengths 516 21.8k | instruction int64 0 3 | solution_c dict |
|---|---|---|---|
221 | <p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>'s and <code>1</code>'s, <em>find the largest square containing only</em> <code>1</code>'s <em>and return its area</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" style="width: 400px; height: 319px;" />
<pre>
<strong>Input:</strong> matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" style="width: 165px; height: 165px;" />
<pre>
<strong>Input:</strong> matrix = [["0","1"],["1","0"]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> matrix = [["0"]]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 300</code></li>
<li><code>matrix[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int maximalSquare(vector<vector<char>>& m) {\n vector<vector<int>> dp(m.size()+1, vector<int>(m[0].size()));\n\t\n\t // preprocess from left side to to signify i,j showing consecutive 1s from horizontal line starting from i,j\n\t for(int i=0;i<m.size();i++) {\n\t\t for(int j=m[0].size()-1;j>=0;j--) {\n\t\t\t if(j == m[0].size()-1) {\n\t\t\t\t dp[i][j] = m[i][j]=='1' ? 1 : 0;\n } else if (m[i][j] == '1') {\n\t\t\t\t dp[i][j] = dp[i][j+1]+1;\n } else {\n\t dp[i][j] = 0;\n }\n }\n }\n\n\n // use monotonic stack to calculate area\n int maxi = 0;\n\n for(int j=0;j<m[0].size();j++) {\n stack<pair<int,int>> s;\n for(int i=0; i<=m.size();i++) {\n // if stack is empty or the new value satisfies increasing stack invariant, push value on stack\n if(s.empty() || s.top().first <= dp[i][j]) {\n s.push(make_pair(dp[i][j], i));\n }\n else {\n int top = i-1;\n while(!s.empty() && s.top().first >= dp[i][j]) {\n auto val = s.top().first;\n s.pop();\n int place = s.empty() ? 0 : s.top().second+1;\n int len = min(val, top-place+1);\n maxi = max(maxi, len*len);\n }\n \n s.push(make_pair(dp[i][j], i));\n \n }\n }\n \n // no need to empty stack since extra 0 in last row will take care of emptying stack \n }\n return maxi;\n }\n};",
"memory": "28300"
} |
221 | <p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>'s and <code>1</code>'s, <em>find the largest square containing only</em> <code>1</code>'s <em>and return its area</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" style="width: 400px; height: 319px;" />
<pre>
<strong>Input:</strong> matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" style="width: 165px; height: 165px;" />
<pre>
<strong>Input:</strong> matrix = [["0","1"],["1","0"]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> matrix = [["0"]]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 300</code></li>
<li><code>matrix[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int maximalSquare(vector<vector<char>>& matrix) {\n struct Data\n {\n int numberOfConsecutiveSquaresLeft = 0;\n int numberOfConsecutiveSquaresUp = 0;\n int sizeOfSquare = 0;\n };\n\n auto data = vector<vector<Data>>(matrix.size() + 1, vector<Data>(matrix[0].size() + 1));\n auto maximumSizeOfSquare = 0;\n\n for (auto y = 1; y <= matrix.size(); ++y)\n {\n for (auto x = 1; x <= matrix[0].size(); ++x)\n {\n if (matrix[y - 1][x - 1] == '1')\n {\n data[y][x].numberOfConsecutiveSquaresLeft = data[y][x - 1].numberOfConsecutiveSquaresLeft + 1;\n data[y][x].numberOfConsecutiveSquaresUp = data[y - 1][x].numberOfConsecutiveSquaresUp + 1;\n // This is a square if numberOfConsecutiveSquaresLeft and numberOfConsecutiveSquaresUp are both\n // at least one larger than the sizeOfSquare in the top left. The size of the new square is the\n // size of the top left square + 1.\n auto shortestDirection = std::min(data[y][x].numberOfConsecutiveSquaresLeft, data[y][x].numberOfConsecutiveSquaresUp);\n if (shortestDirection >= data[y - 1][x - 1].sizeOfSquare + 1)\n {\n data[y][x].sizeOfSquare = data[y - 1][x - 1].sizeOfSquare + 1;\n }\n else\n {\n data[y][x].sizeOfSquare = std::min(shortestDirection, data[y - 1][x - 1].sizeOfSquare);\n }\n\n maximumSizeOfSquare = std::max(maximumSizeOfSquare, data[y][x].sizeOfSquare);\n\n // If we can't continue to expand the square, we can at least make a smaller square up to the\n // limits of std::min(numberOfConsecutiveSquaresLeft, numberOfConsecutiveSquaresUp)\n\n // [[\"0\",\"0\",\"0\",\"1\"],\n // [\"1\",\"1\",\"0\",\"1\"],\n // [\"1\",\"1\",\"1\",\"1\"],\n // [\"0\",\"1\",\"1\",\"1\"],\n // [\"0\",\"1\",\"1\",\"1\"]]\n }\n }\n }\n\n return maximumSizeOfSquare * maximumSizeOfSquare;\n }\n};",
"memory": "28400"
} |
221 | <p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>'s and <code>1</code>'s, <em>find the largest square containing only</em> <code>1</code>'s <em>and return its area</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" style="width: 400px; height: 319px;" />
<pre>
<strong>Input:</strong> matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" style="width: 165px; height: 165px;" />
<pre>
<strong>Input:</strong> matrix = [["0","1"],["1","0"]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> matrix = [["0"]]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 300</code></li>
<li><code>matrix[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int maximalSquare(vector<vector<char>>& matrix) {\n int m = matrix.size();\n int n = matrix[0].size();\n vector<int> h(n + 2);\n int ans = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (matrix[i][j] == '0') h[j + 1] = 0;\n else h[j + 1]++;\n }\n\n vector<int> s = {0};\n for (int j = 1; j <= n + 1; j++) {\n while (h[s.back()] > h[j]) {\n int tmp = h[s.back()];\n s.pop_back();\n int a = min(tmp, j - s.back() - 1);\n ans = max(ans, a * a);\n }\n s.push_back(j);\n }\n }\n return ans;\n }\n};",
"memory": "28500"
} |
221 | <p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>'s and <code>1</code>'s, <em>find the largest square containing only</em> <code>1</code>'s <em>and return its area</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" style="width: 400px; height: 319px;" />
<pre>
<strong>Input:</strong> matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" style="width: 165px; height: 165px;" />
<pre>
<strong>Input:</strong> matrix = [["0","1"],["1","0"]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> matrix = [["0"]]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 300</code></li>
<li><code>matrix[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int solve(vector<vector<char>>& matrix, int i, int j){\n int n = matrix.size();\n // base case 20 oct 2023\n if( i >= n || j >= matrix[0].size()){\n return 0;\n }\n\n // initialise the pointer right , diagonal , down\n int right = solve( matrix, i , j+1);\n int diagonal = solve(matrix, i+1, j);\n int down = solve(matrix, i+1, j+1);\n\n int ans = INT_MIN;\n for(int k=0; k<n; k++){\n max(right, max(diagonal, down));\n }\n return ans;\n}\n int solveMem(vector<vector<char>>& matrix, int i, int j, vector<vector<int>> &dp){\n int n = matrix.size();\n int m = matrix[0].size();\n\n if( i >= n || j >= m){\n return 0;\n }\n if(dp[i][j] != -1){\n return dp[i][j];\n }\n int right = solveMem( matrix, i , j+1, dp);\n int diagonal = solveMem(matrix, i+1, j, dp);\n int down = solveMem(matrix, i+1, j+1, dp);\n\n // int ans = INT_MAX;\n // for(int k=0; k<n; k++){\n // max(ans, dp[i][j]);\n // }\n\n if(matrix[i][j] == '1'){\n dp[i][j] = 1 + min(right, min(down , diagonal));\n }else{\n dp[i][j] = 0;\n }\n \n return dp[i][j];\n }\n\n int solveTab(vector<vector<char>> matrix){\n\n // int n = matrix.size();\n\n int row = matrix.size();\n int col = matrix[0].size();\n vector<vector<int>> dp(row+1, vector<int> (col+1, 0));\n\n int maxi =0;\n for(int i = row -1; i>=0; i--){\n for(int j = col-1; j>=0; j--){\n \n int right = dp[i][j+1];\n int diagonal = dp[i+1][j];\n int down = dp[i+1][j+1];\n\n\n if(matrix[i][j] == '1'){\n dp[i][j] = 1 + min(right, min(down , diagonal));\n maxi = max(maxi, dp[i][j]);\n }\n else{ \n dp[i][j] = 0;\n }\n } \n } \n return maxi;\n }\n int maximalSquare(vector<vector<char>>& matrix) {\n // int n = matrix.size();\n \n int maxi =0;\n return solveTab(matrix) * solveTab(matrix);\n // return maxi; \n }\n};",
"memory": "28600"
} |
221 | <p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>'s and <code>1</code>'s, <em>find the largest square containing only</em> <code>1</code>'s <em>and return its area</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" style="width: 400px; height: 319px;" />
<pre>
<strong>Input:</strong> matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" style="width: 165px; height: 165px;" />
<pre>
<strong>Input:</strong> matrix = [["0","1"],["1","0"]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> matrix = [["0"]]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 300</code></li>
<li><code>matrix[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n using p=pair<int, int>;\n int maximalSquare(vector<vector<char>>& matrix) {\n int r=matrix.size();\n int c=matrix[0].size();\n vector<vector<int>> vec(r, vector<int>(c));\n for(auto y=0; y<r; y++)\n {\n for(auto x=0; x<c;x++)\n {\n vec[y][x]=matrix[y][x]-'0';\n if(x && vec[y][x])\n vec[y][x]+=vec[y][x-1];\n }\n }\n int ans=0;\n for(auto x=0; x<c;x++)\n {\n int l=0;\n priority_queue<p, vector<p>, greater<p>> pq;\n for(int y=0; y<r;y++)\n {\n\n if(vec[y][x])\n {\n pq.push({vec[y][x], y});\n while(pq.top().first<y-l+1)\n {\n l=max(l, pq.top().second+1);\n pq.pop();\n }\n //cout<<y-l+1<<\" \";\n ans=max(ans, y-l+1);\n }\n else\n {\n while(pq.size())\n pq.pop();\n l=y+1;\n }\n }\n }\n return ans*ans;\n }\n};",
"memory": "28700"
} |
221 | <p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>'s and <code>1</code>'s, <em>find the largest square containing only</em> <code>1</code>'s <em>and return its area</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" style="width: 400px; height: 319px;" />
<pre>
<strong>Input:</strong> matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" style="width: 165px; height: 165px;" />
<pre>
<strong>Input:</strong> matrix = [["0","1"],["1","0"]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> matrix = [["0"]]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 300</code></li>
<li><code>matrix[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n using p=pair<int, int>;\n int maximalSquare(vector<vector<char>>& matrix) {\n int r=matrix.size();\n int c=matrix[0].size();\n vector<vector<int>> vec(r, vector<int>(c));\n for(auto y=0; y<r; y++)\n {\n for(auto x=0; x<c;x++)\n {\n vec[y][x]=matrix[y][x]-'0';\n if(x && vec[y][x])\n vec[y][x]+=vec[y][x-1];\n }\n }\n int ans=0;\n for(auto x=0; x<c;x++)\n {\n int l=0;\n priority_queue<p, vector<p>, greater<p>> pq;\n for(int y=0; y<r;y++)\n {\n\n if(vec[y][x])\n {\n pq.push({vec[y][x], y});\n while(pq.top().first<y-l+1)\n {\n l=max(l, pq.top().second+1);\n pq.pop();\n }\n ans=max(ans, y-l+1);\n }\n else\n {\n while(pq.size())\n pq.pop();\n l=y+1;\n }\n }\n }\n return ans*ans;\n }\n};",
"memory": "28800"
} |
221 | <p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>'s and <code>1</code>'s, <em>find the largest square containing only</em> <code>1</code>'s <em>and return its area</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" style="width: 400px; height: 319px;" />
<pre>
<strong>Input:</strong> matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" style="width: 165px; height: 165px;" />
<pre>
<strong>Input:</strong> matrix = [["0","1"],["1","0"]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> matrix = [["0"]]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 300</code></li>
<li><code>matrix[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int largestSqInHist(vector<int>& height) {\n int area = 0;\n int n = height.size();\n stack<int> st;\n int width = 0;\n int mini = INT_MAX;\n int maxsq = 0;\n\n for(int i = 0; i <= n; i++) {\n while(!st.empty() && (i == n || height[st.top()] > height[i])) {\n int topHeight = height[st.top()];\n st.pop();\n if(st.empty())\n width = i;\n else\n width = i - st.top() - 1;\n\n int side = min(width, topHeight);\n maxsq = max(maxsq, side * side);\n }\n st.push(i);\n }\n return maxsq;\n }\n\n int maximalSquare(vector<vector<char>>& mat) {\n if(mat.empty() || mat[0].empty()) return 0;\n\n int n = mat.size();\n int m = mat[0].size();\n\n vector<vector<int>> temp(n, vector<int>(m, 0));\n\n for(int j = 0; j < m; j++) {\n int sum = 0;\n for(int i = 0; i < n; i++) {\n sum += mat[i][j] - '0';\n if(mat[i][j] == '0')\n sum = 0;\n temp[i][j] = sum;\n }\n }\n\n int maxsq = 0;\n for(int i = 0; i < n; i++) {\n maxsq = max(maxsq, largestSqInHist(temp[i]));\n }\n\n return maxsq;\n }\n};\n",
"memory": "28900"
} |
223 | <p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p>
<p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p>
<p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="Rectangle Area" src="https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png" style="width: 700px; height: 365px;" />
<pre>
<strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
<strong>Output:</strong> 45
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>-10<sup>4</sup> <= ax1 <= ax2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= ay1 <= ay2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= bx1 <= bx2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= by1 <= by2 <= 10<sup>4</sup></code></li>
</ul>
| 0 | {
"code": "class Solution {\npublic:\n int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n int ans=0;\n\n ans+=(ay2-ay1)*(ax2-ax1)+(by2-by1)*(bx2-bx1);\n\n int len=min(ax2,bx2)-max(ax1,bx1);\n int wid=min(ay2,by2)-max(ay1,by1);\n if(len<0 || wid<0)\n return ans;\n return ans-len*wid;\n\n \n \n \n }\n};",
"memory": "9600"
} |
223 | <p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p>
<p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p>
<p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="Rectangle Area" src="https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png" style="width: 700px; height: 365px;" />
<pre>
<strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
<strong>Output:</strong> 45
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>-10<sup>4</sup> <= ax1 <= ax2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= ay1 <= ay2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= bx1 <= bx2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= by1 <= by2 <= 10<sup>4</sup></code></li>
</ul>
| 0 | {
"code": "class Solution {\npublic:\n int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n int x = max(0,min(ax2,bx2)-max(ax1,bx1));\n int y = max(0,min(ay2,by2)-max(ay1,by1));\n return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - x*y;\n }\n};",
"memory": "9700"
} |
223 | <p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p>
<p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p>
<p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="Rectangle Area" src="https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png" style="width: 700px; height: 365px;" />
<pre>
<strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
<strong>Output:</strong> 45
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>-10<sup>4</sup> <= ax1 <= ax2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= ay1 <= ay2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= bx1 <= bx2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= by1 <= by2 <= 10<sup>4</sup></code></li>
</ul>
| 0 | {
"code": "class Solution {\npublic:\n int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n int area1 = (ax2 - ax1) * (ay2 - ay1);\n int area2 = (bx2 - bx1) * (by2 - by1);\n int overlapWidth = min(ax2, bx2) - max(ax1, bx1);\n int overlapHeight = min(ay2, by2) - max(ay1, by1);\n int overlapArea = 0;\n if (overlapWidth > 0 && overlapHeight > 0) {\n overlapArea = overlapWidth * overlapHeight;\n }\n return area1 + area2 - overlapArea;\n }\n};\n",
"memory": "9700"
} |
223 | <p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p>
<p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p>
<p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="Rectangle Area" src="https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png" style="width: 700px; height: 365px;" />
<pre>
<strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
<strong>Output:</strong> 45
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>-10<sup>4</sup> <= ax1 <= ax2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= ay1 <= ay2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= bx1 <= bx2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= by1 <= by2 <= 10<sup>4</sup></code></li>
</ul>
| 0 | {
"code": "class Solution {\npublic:\n int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n int area1 = (ax2 - ax1) * (ay2 - ay1);\n int area2 = (bx2 - bx1) * (by2 - by1);\n int overlappedArea = max(0, min(ax2, bx2) - max(ax1, bx1)) * max(0, min(ay2, by2) - max(ay1, by1));\n return area1 + area2 - overlappedArea;\n }\n};",
"memory": "9800"
} |
223 | <p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p>
<p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p>
<p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="Rectangle Area" src="https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png" style="width: 700px; height: 365px;" />
<pre>
<strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
<strong>Output:</strong> 45
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>-10<sup>4</sup> <= ax1 <= ax2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= ay1 <= ay2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= bx1 <= bx2 <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= by1 <= by2 <= 10<sup>4</sup></code></li>
</ul>
| 0 | {
"code": "class Solution {\npublic:\n int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n\n int l=-max(ax1,bx1)+min(ax2,bx2);\n int b=-max(ay1,by1)+min(ay2,by2);\n int overlap=0;\n if(l>=0 && b>=0)\n overlap=l*b;\n int total=abs(ax2-ax1)*abs(ay2-ay1)+abs(bx2-bx1)*abs(by2-by1);\n return total-overlap;\n \n }\n};",
"memory": "9800"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 0 | {
"code": "\nclass Solution {\npublic:\n int calculate(const std::string& s) {\n idx = 0;\n return calc(s);\n }\n\nprivate:\n int idx; // Index for parsing the string\n\n int calc(const std::string& s) {\n int num = 0, res = 0;\n int sign = 1; // 1 for positive, -1 for negative\n\n while (idx < s.length()) {\n char c = s[idx++];\n \n // If it's a digit, construct the number\n if (c >= '0' && c <= '9') {\n num = num * 10 + (c - '0');\n } \n // Handle open parenthesis\n else if (c == '(') {\n num = calc(s); // Recursive call for the sub-expression\n } \n // Handle close parenthesis\n else if (c == ')') {\n return res + num * sign; // Return result when closing parenthesis is encountered\n } \n // Handle operators\n else if (c == '+' || c == '-') {\n res += num * sign; // Apply the previous number with its sign\n num = 0; // Reset the number\n sign = (c == '-') ? -1 : 1; // Update sign based on the current operator\n } \n // Skip spaces\n else if (c == ' ') {\n continue;\n }\n }\n\n // Handle the last number after the loop ends\n res += num * sign;\n return res;\n }\n};\n",
"memory": "9368"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 0 | {
"code": "class Solution {\npublic:\n int calculate(string &s) {\n int ans = 0, sign = 1, number = 0; // `number` stores the current number\n stack<int> stk;\n stk.push(sign);\n for (char c : s) {\n if (isdigit(c)) number = number * 10 + (c - '0');\n else if (c == '+' || c == '-') { // (¶)\n ans += sign * number;\n number = 0;\n sign = stk.top() * (c == '+' ? 1 : -1); // note that `sign` can only be 1 or –1 (§)\n }\n else if (c == '(') stk.push(sign);\n else if (c == ')') stk.pop(); // the influence of the sign at the top of the stack has ended\n }\n ans += sign * number;\n return ans;\n }\n}; // Calculatrice de base 基本的な計算機(・計算器・けいさんき)[電卓・でんたく:「電子式卓上計算機(でんししきたくじょうけいさんき)また電子式卓上加算機」の略]\n// Comparison: in the previous submission, we used the stack to store operands and operators (as well as results): when we encounter a right parenthesis (ie ')'), we start doing the calculation, popping from the stack until we encounter a left parenthesis. Essentially, we only update the answer when we encounter a right parenthesis (and after the loop ends).\n// (§) But here, we update the answer for each number (and after the loop ends). Conceptually, we are (開括號) opening the parentheses on-the-fly. To achieve this, we only use the stack to store the signs so that we can check, for each number, what is the sign outside its closest left parenthesis. For instance, consider the input string \"–2–(1–(4+5–(–7–2)+2)–3)–(6+8)\". Note that the expression E1 = –2–(1–(4+5–(–7–2)+2)–3)–(6+8) is equivalent to the expression E2 = –2–1+4+5+7+2+2+3–6–8. When we encounter the first left parenthesis in E1, we push into the stack a minus sign, so when we encouter 1, we know its sign is negative (which is the same as the sign of 1 in E2). When we encounter the second left parenthesis, we see the sign in front of it is a minus sign, and we check the top of the stack, which is also a minus sign, we know the sign should be positive so we push a plus sign into the stack: thus when we encounter 4, we know it is positive (which is the same as the sign of 4 in E2)\n// So, here the algorithm is essentially doing this:\n// –2–1+4+5+7+2+2+3–6–8\n// = –3+4+5+7+2+2+3–6–8\n// = 1+5+7+2+2+3–6–8\n// = 6+7+2+2+3–6–8\n// = 13+2+2+3–6–8\n// = 15+2+3–6–8\n// = 17+3–6–8\n// = 20–6–8\n// = 14–8\n// = 6\n// For comparison, in the previous submission, we are essentially doing this: \n// –2–(1–(4+5–(–7–2)+2)–3)–(6+8)\n// = –2–(1–(4+5––9+2)–3)–(6+8)\n// = –2–(1–(4+5+9+2)–3)–(6+8)\n// = –2–(1–(4+5+11)–3)–(6+8)\n// = –2–(1–(4+16)–3)–(6+8)\n// = –2–(1–20–3)–(6+8)\n// = –2–(1–23)–(6+8)\n// = –2––22–(6+8)\n// = –2––22–14\n// = –2+22–14\n// = –2+8\n// = 6\n// (¶) we deal with the current number. and determine the sign of the next number",
"memory": "9368"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 2 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<pair<int, int>> valueStore;\n\n int result = 0;\n int sign = 1;\n\n for (int i = 0; i < s.length(); i++) {\n if (isdigit(s[i])) {\n int num = s[i] - '0';\n while (i < s.length() - 1 && isdigit(s[i+1])) {\n num = (num * 10) + (s[++i] - '0');\n }\n result += (sign * num);\n sign = 1;\n } else if (s[i] == '-') {\n sign = -1;\n } else if (s[i] == '(') {\n valueStore.push({result, sign});\n result = 0;\n sign = 1;\n } else if (s[i] == ')') {\n auto [topSum, topSign] = valueStore.top();\n valueStore.pop();\n result = (topSign * result) + topSum;\n }\n }\n\n return result;\n }\n};",
"memory": "10306"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 2 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<pair<int,int>> st; // pair(prev_calc_value , sign before next bracket () )\n \n long long int sum = 0;\n int sign = +1;\n \n for(int i = 0 ; i < s.size() ; ++i)\n {\n char ch = s[i];\n \n if(isdigit(ch))\n {\n long long int num = 0;\n while(i < s.size() and isdigit(s[i]))\n {\n num = (num * 10) + s[i] - '0';\n i++;\n }\n i--; // as for loop also increase i , so if we don't decrease i here a sign will be skipped\n sum += (num * sign);\n sign = +1; // reseting sign\n }\n else if(ch == '(')\n {\n // Saving current state of (sum , sign) in stack\n st.push(make_pair(sum , sign));\n \n // Reseting sum and sign for inner bracket calculation\n sum = 0; \n sign = +1;\n }\n else if(ch == ')')\n {\n sum = st.top().first + (st.top().second * sum);\n st.pop();\n }\n else if(ch == '-')\n {\n // toggle sign\n sign = (-1 * sign);\n }\n }\n return sum;\n }\n};",
"memory": "10306"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 2 | {
"code": "class Calc {\npublic:\n Calc(string& source) {\n s = source;\n s.erase(std::remove(s.begin(), s.end(), ' '), s.end());\n }\n\n int eval() {\n return eval_expr();\n }\n\nprivate:\n string s;\n size_t i{ 0 };\n\n int eval_expr() {\n int sum{ 0 };\n while (has_next()) {\n if (peek() == ')') {\n advance();\n break;\n }\n int term{ 0 };\n bool has_minus{ false };\n if (peek() == '-') {\n has_minus = true;\n advance();\n }\n if (peek() == '(') {\n advance();\n term = eval_expr();\n } else if (std::isdigit(peek())) {\n term = eval_number();\n } else if (peek() == '+') {\n advance();\n continue;\n }\n sum += has_minus ? -term : term;\n }\n return sum;\n }\n\n int eval_number() {\n std::string digits{};\n while (std::isdigit(peek())) {\n digits.push_back(peek());\n advance();\n }\n return std::stoi(digits);\n }\n\n bool has_next() {\n return i < s.length();\n }\n\n char peek() {\n return s[i];\n }\n\n void advance() {\n i++;\n }\n};\n\nclass Solution {\npublic:\n int calculate(string s) {\n return Calc{ s }.eval();\n }\n};",
"memory": "11243"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 2 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n vector<pair<bool, pair<int, char>>> store;\n string curr_num_str = \"\";\n bool num_valid = 0;\n int curr_num = 0;\n for (char c : s) {\n if (isdigit(c)) {\n curr_num_str += c;\n continue;\n }\n num_valid = 0;\n if (curr_num_str != \"\") {\n curr_num = stoi(curr_num_str);\n curr_num_str = \"\";\n num_valid = 1;\n }\n if (num_valid || c == ')') {\n while (!store.empty()) {\n if (store[size(store)-1].first) {\n if (store[size(store)-1].second.second == '(') {\n if (c != ')') {\n break;\n }\n c = ' ';\n }\n if (store[size(store)-1].second.second == '-' && num_valid) {\n curr_num = -curr_num;\n }\n } else {\n if (!num_valid) {\n num_valid = 1;\n curr_num = store[size(store)-1].second.first;\n } else {\n curr_num = store[size(store)-1].second.first + curr_num;\n }\n }\n store.pop_back();\n }\n }\n if (num_valid) {\n store.push_back(pair<bool, pair<int, char>>(0, pair<int, char>(curr_num, 'x')));\n } \n if (c != ' ' && c != ')') {\n store.push_back(pair<bool, pair<int, char>>(1, pair<int, char>(0, c)));\n }\n }\n if (curr_num_str != \"\") {\n curr_num = stoi(curr_num_str);\n store.push_back(pair<bool, pair<int, char>>(0, pair<int, char>(curr_num, ' ')));\n curr_num_str = \"\";\n }\n num_valid = 0;\n\n while (!store.empty()) {\n if (store[size(store)-1].first) {\n if (store[size(store)-1].second.second == '-' && num_valid) {\n curr_num = -curr_num;\n }\n } else {\n if (!num_valid) {\n num_valid = 1;\n curr_num = store[size(store)-1].second.first;\n } else {\n curr_num = store[size(store)-1].second.first + curr_num;\n }\n }\n store.pop_back();\n }\n if (num_valid) store.push_back(pair<bool, pair<int, char>>(0, pair<int, char>(curr_num, ' ')));\n\n return store[size(store)-1].second.first;\n }\n};",
"memory": "11243"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n vector<char> pos;\n vector<int> eval;\n int i = 0;\n while (i < s.length()){\n // cout << \"hi0 \" << s[i] << endl;\n if (s[i] == '(') {\n pos.push_back('(');\n i++;\n }\n else if (s[i] == '+') {\n pos.push_back('+');\n i++;\n }\n else if (s[i] == '-') {\n pos.push_back('-');\n i++;\n }\n else if ( '0' <= s[i] && s[i] <= '9') { \n string N = \"\";\n N += s[i];\n while (i+1 < s.length() && '0' <= s[i+1] && s[i+1] <= '9'){\n N += s[i+1];\n i++;\n // cout << \"hi\" << endl;\n }\n i++;\n // cout << N << \" \" << N.length() << endl;\n int n = stoi(N);\n int top = pos.size()-1;\n int etop = eval.size()-1;\n if (top < 0){\n eval.push_back(n);\n pos.push_back('n');\n }\n else if (pos[top] == '+'){\n eval[etop] += n;\n pos.pop_back();\n }\n else if (pos[top] == '-'){\n if (top-1 >= 0 && pos[top-1] == 'n'){\n eval[etop] -= n;\n pos.pop_back();\n }\n else {\n eval.push_back(-n);\n pos.pop_back();\n pos.push_back('n');\n }\n }\n else {\n pos.push_back('n');\n eval.push_back(n);\n }\n }\n else if (s[i] == ')'){\n int top = pos.size()-3;\n int etop = eval.size()-1;\n int n = eval[etop];\n i++;\n pos.pop_back();\n pos.pop_back();\n eval.pop_back();\n // cout << \"hel \" << n << \" \" << top << endl;\n if (top < 0){\n // cout << top << \" k \" << etop << endl;\n eval.push_back(n);\n pos.push_back('n');\n }\n else if (pos[top] == '+'){\n eval[etop-1] += n;\n pos.pop_back();\n }\n else if (pos[top] == '-'){\n if (top - 1 >= 0 && pos[top-1] == 'n'){\n eval[etop-1] -= n;\n pos.pop_back();\n }\n else {\n eval.push_back(-n);\n pos.pop_back();\n pos.push_back('n');\n }\n }\n else {\n pos.push_back('n');\n eval.push_back(n);\n }\n }\n else i++;\n // for (int h = 0; h < eval.size(); h++){\n // cout << eval[h] << \" \";\n // }\n // cout << endl;\n // for (int h = 0; h < pos.size(); h++){\n // cout << pos[h] << \" \";\n // }\n // cout << endl;\n }\n return eval[0];\n }\n};",
"memory": "12181"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<int> values;\n stack<char> ops;\n\n int current_value = 0;\n bool negate = false;\n bool last_token_was_op = true;\n for (int i = 0; i < s.length(); i++) {\n if (s[i] == ' ') continue;\n\n if (s[i] >= '0' && s[i] <= '9') {\n while (i < s.length() && s[i] >= '0' && s[i] <= '9') {\n current_value *= 10;\n current_value += s[i] - '0';\n i++;\n }\n // if (negate) {\n // current_value *= -1;\n // negate = false;\n // }\n values.push(current_value);\n current_value = 0;\n i--;\n last_token_was_op = false;\n } else if (last_token_was_op && s[i] == '-') {\n values.push(0);\n ops.push('-');\n } else if (s[i] == '+' || s[i] == '-') {\n while (!ops.empty() && ops.top() != '(') {\n int b = values.top(); values.pop();\n int a = values.top(); values.pop();\n char op = ops.top(); ops.pop();\n\n if (op == '+') values.push(a + b);\n else if (op == '-') values.push(a - b);\n }\n\n ops.push(s[i]);\n last_token_was_op = true;\n } else if (s[i] == '(') {\n ops.push(s[i]);\n last_token_was_op = true;\n } else if (s[i] == ')') {\n while (!ops.empty() && ops.top() != '(') {\n int b = values.top(); values.pop();\n int a = values.top(); values.pop();\n char op = ops.top(); ops.pop();\n\n if (op == '+') values.push(a + b);\n else if (op == '-') values.push(a - b);\n }\n\n // if (negate) {\n // int v = values.top(); values.pop();\n // values.push(-v);\n // negate = false;\n // }\n\n ops.pop();\n last_token_was_op = false;\n }\n }\n\n while (!ops.empty()) {\n int b = values.top(); values.pop();\n int a = values.top(); values.pop();\n char op = ops.top(); ops.pop();\n\n if (op == '+') values.push(a + b);\n else if (op == '-') values.push(a - b);\n }\n\n return values.top();\n }\n};",
"memory": "12181"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int solve(string &s,int l, int r){\n int res = 0;\n for(int i=l;i<=r;i++){\n if((s[i]=='-'||s[i]=='+')){\n int m = (s[i]=='-')? -1 : 1; i++;\n while(i<=r&&s[i]==' ') i++;\n if(s[i]=='('){\n int j = i+1; int ct=1;\n while(j<=r&&ct!=0){\n if(s[j]==')') ct--;\n else if(s[j]=='(') ct++;\n j++;\n }\n res += m*solve(s,i+1,j-2);\n i = j-1; \n }\n else {\n while(i<=r&&s[i]==' ') i++;\n int j = i;\n while(j<=r&&s[j]<='9'&&s[j]>='0') j++;\n res += m*stoi(s.substr(i,j-i));\n i=j-1;\n }\n }\n else if(s[i]=='('){\n int j = i+1; int ct = 1;\n while(j<=r&&ct!=0){\n if(s[j]=='(') ct++;\n else if(s[j]==')') ct--;\n j++;\n }\n res += solve(s,i+1,j-2);\n i=j-1; \n }\n else if(s[i]!=' ') {\n int f = (s[i]=='-')? -1 : 1;\n if(s[i]=='+'||s[i]=='-') i++;\n while(i<=r&&s[i]==' ') i++;\n int j = i;\n while(j<=r&&s[j]<='9'&&s[j]>='0') j++;\n res += f*stoi(s.substr(i,j-i));\n i = j-1;\n }\n }\n return res;\n }\n int calculate(string s) {\n ios::sync_with_stdio(0); cin.tie(0);\n return solve(s,0,s.size()-1);\n }\n};",
"memory": "13118"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int solve(string &s,int l, int r){\n int res = 0;\n for(int i=l;i<=r;i++){\n if((s[i]=='-'||s[i]=='+')){\n int m = (s[i]=='-')? -1 : 1; i++;\n if(s[i]=='('){\n int j = i+1; int ct=1;\n while(j<=r&&ct!=0){\n if(s[j]==')') ct--;\n else if(s[j]=='(') ct++;\n j++;\n }\n res += m*solve(s,i+1,j-2);\n i = j-1; \n }\n else {\n int j = i;\n while(j<=r&&s[j]<='9'&&s[j]>='0') j++;\n res += m*stoi(s.substr(i,j-i));\n i=j-1;\n }\n }\n else if(s[i]=='('){\n int j = i+1; int ct = 1;\n while(j<=r&&ct!=0){\n if(s[j]=='(') ct++;\n else if(s[j]==')') ct--;\n j++;\n }\n res += solve(s,i+1,j-2);\n i=j-1; \n }\n else {\n int f = (s[i]=='-')? -1 : 1;\n if(s[i]=='+'||s[i]=='-') i++;\n int j = i;\n while(j<=r&&s[j]<='9'&&s[j]>='0') j++;\n res += f*stoi(s.substr(i,j-i));\n i = j-1;\n }\n }\n return res;\n }\n int calculate(string s) {\n ios::sync_with_stdio(0); cin.tie(0);\n int i = 0;\n while(i!=s.size()){\n if(s[i]==' ') s.erase(i,1);\n else i++;\n }\n return solve(s,0,s.size()-1);\n }\n};",
"memory": "13118"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int opposign(int num){\n return -num;\n }\n string calculated(string &s){\n int sign=1,i=1;\n if(s[0]!='-'){\n sign=0,i=0;\n }\n int ans=0;\n while(i<s.size() and s[i]>='0' and s[i]<='9'){\n ans=ans*10+(s[i]-'0');\n i++;\n }\n if(sign) ans=opposign(ans);\n // cout<<\"ans \"<<ans<<endl;\n while(i<s.size()){\n if(s[i]=='-'){\n sign=1;\n }\n else{\n sign=0;\n }\n int val=0;\n i++;\n while(i<s.size() and s[i]>='0' and s[i]<='9'){\n val=val*10+(s[i]-'0');\n i++;\n }\n // cout<<\"val \"<<val<<endl;\n if(sign) ans-=val;\n else ans+=val;\n }\n return to_string(ans);\n }\n void push(stack<char>&st,string &s,int start){\n while(start<s.size()) st.push(s[start]),start++;\n }\n int cal(string &temp){\n stack<char>st;\n for(int i=0;i<temp.size();i++){\n if(temp[i]==')'){\n string newtemp=\"\";\n while(st.top()!='('){\n newtemp+=st.top();\n st.pop();\n }\n reverse(newtemp.begin(),newtemp.end());\n st.pop();\n string newres=calculated(newtemp);\n if(st.size()==0){\n push(st,newres,0);\n }\n else{\n if(st.top()=='-'){\n if(newres.size()>0){\n if(newres[0]=='-'){\n st.pop();\n st.push('+');\n push(st,newres,1);\n }\n else{\n push(st,newres,0);\n }\n }\n }\n else{\n push(st,newres,0);\n }\n }\n }\n else{\n st.push(temp[i]);\n }\n }\n string ans=\"\";\n while(st.size()>0){\n ans+=st.top(),st.pop();\n }\n reverse(ans.begin(),ans.end());\n //cout<<ans<<endl;\n // ans=calculated(ans);\n // for(auto it:ans){\n // cout<<it<<\" \";\n // }\n return stoi(calculated(ans));\n }\n int calculate(string s) {\n string temp=\"\";\n string temp1=\"\";\n for(int i=0;i<s.size();i++){\n if(s[i]==' ') continue;\n temp+=s[i];\n }\n //cout<<calculated(temp)<<endl;\n return cal(temp);\n }\n};",
"memory": "14056"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int precedence(char ch) {\n if(ch == '+' || ch == '-') {\n return 1;\n }\n if(ch == 'X') {\n return 2;\n }\n return 0; // 0 for (\n }\n\n bool isHigherPrecedence(char curr, char prev) {\n if(curr == '+' || curr == '-') {\n return precedence(curr) > precedence(prev);\n }\n return precedence(curr) >= precedence(prev);\n }\n\n bool isDigit(char ch) {\n return ch >= '0' && ch <= '9';\n }\n\n string converToPostfix(string s) {\n string expr = \"\";\n stack<char> ops;\n int n = s.size();\n bool wasLastOperator = true;\n for(int i=0;i<n;i++) {\n if(s[i] == ' ') {\n continue;\n }\n if(isDigit(s[i])) {\n expr += s[i];\n if(i == n-1 || !isDigit(s[i+1])) {\n expr += \"_\";\n }\n wasLastOperator = false;\n continue;\n }\n if(s[i] == '(') {\n ops.push('(');\n }\n else if(s[i] == ')') {\n while(ops.top() != '(') {\n expr += ops.top();\n ops.pop();\n }\n ops.pop();\n } else {\n if(s[i] == '-' && wasLastOperator) {\n s[i] = 'X';\n }\n while(!ops.empty() && !isHigherPrecedence(s[i], ops.top())) {\n expr += ops.top();\n ops.pop();\n }\n ops.push(s[i]);\n wasLastOperator = true;\n }\n }\n while(!ops.empty()) {\n expr += ops.top();\n ops.pop();\n }\n return expr;\n }\n\n int evalPostfixExpr(string s) {\n stack<int> operands;\n int n = s.size(), op1, op2;\n string curr = \"\";\n for(int i=0;i<n;i++) {\n if(isDigit(s[i])) {\n curr += s[i];\n }else if(s[i] == '_') {\n operands.push(stoi(curr));\n curr = \"\";\n } else if(s[i] == '+') {\n op2 = operands.top();\n operands.pop();\n op1 = operands.top();\n operands.pop();\n operands.push(op1 + op2);\n } else if(s[i] == '-') {\n op2 = operands.top();\n operands.pop();\n op1 = operands.top();\n operands.pop();\n operands.push(op1 - op2);\n } else if (s[i] == 'X') {\n op1 = operands.top();\n operands.pop();\n operands.push(op1*-1);\n }\n }\n return operands.top();\n }\n\n int calculate(string s) {\n string expr = converToPostfix(s);\n // cout<<\"Postfix - \"<<expr<<endl;\n return evalPostfixExpr(expr);\n }\n};",
"memory": "14056"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "//stack for char\nclass Solution {\npublic:\n int calculate(string s) {\n int n = 0;\n int operand = 0;\n stack<variant<int, char>> st;\n\n for(int i = s.size()-1; i >= 0; i--){\n char it = s[i];\n\n\n if(isdigit(it)){\n operand += (pow(10,n)*(it - '0'));\n n++;\n }\n else if(it != ' '){\n if(n != 0){\n st.push(operand);\n operand= 0;\n n = 0;\n }\n\n if( it == '('){\n int res = evaluate(st);\n st.pop();\n st.push(res);\n }\n else{\n st.push(it);\n }\n }\n }\n\n if(n!=0){\n st.push(operand);\n }\n\n return evaluate(st);\n }\n\n int evaluate( stack<variant<int, char>>& st){\n \n if(st.empty() || holds_alternative<char>(st.top())){\n st.push(0);\n }\n\n int res = get<int>(st.top()); st.pop();\n\n while(!st.empty() && holds_alternative<char>(st.top()) && get<char>(st.top()) != ')'){\n char sign = get<char>(st.top());\n if(sign == '+'){\n st.pop();\n res += get<int>(st.top());\n st.pop();\n }\n else{\n st.pop();\n res -= get<int>(st.top());\n st.pop();\n }\n }\n return res;\n }\n\n};",
"memory": "14993"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "#pragma GCC optimize (\"Ofast\")\n#pragma GCC optimize (\"O3\", \"unroll-loops\", \"-ffloat-store\")\n#pragma GCC target(\"avx,mmx,sse2,sse3,sse4\")\n\n// \"_\": A lambda function to enable faster I/O operations\nauto _=[]()noexcept{ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);return 0;}();\n\n#include <string>\n#include <stack>\n#include <any>\n\n\nusing namespace std;\n\nclass Solution {\npublic:\n int calculate(string s) {\n stack<any> stack;\n int num = 0;\n int sign = 1;\n\n for (char c: s) {\n if (isdigit(c)) {\n num = 10 * num + int(c - '0');\n } else if (c == '+' || c == '-') {\n stack.push(sign * num);\n num = 0;\n sign = (c == '+') ? 1 : -1;\n } else if (c == '(') {\n stack.push(sign);\n stack.push('(');\n sign = 1;\n } else if (c == ')') {\n stack.push(sign * num);\n num = 0;\n while (!stack.empty()) {\n any val = stack.top();\n if (val.type() == typeid(char)) {\n if (any_cast<char>(val) == '(')\n break;\n } else if (val.type() == typeid(int)) {\n num += any_cast<int>(val);\n stack.pop();\n }\n }\n\n if (!stack.empty()) {\n any val = stack.top();\n if (val.type() == typeid(char)) {\n if (any_cast<char>(val) == '(') {\n stack.pop();\n }\n }\n }\n\n if (!stack.empty()) {\n sign = any_cast<int>(stack.top());\n stack.pop();\n }\n }\n }\n\n int sumOfStack = 0;\n while (!stack.empty()) {\n sumOfStack += any_cast<int>(stack.top());\n stack.pop();\n }\n \n return (sign * num) + sumOfStack;\n }\n};",
"memory": "14993"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n vector<pair<int,int>> ts;\n for(int i = 0;i < s.size();i++){\n if(s[i] == ' ')continue;\n else if(s[i] == '-' && (i == 0 || ts.back().second == '(' )){\n ts.push_back({0,0});\n ts.push_back({0,'-'});\n }\n else if(s[i] >= '0' && s[i] <= '9'){\n int res = 0;\n while(i < s.size() && s[i] >= '0' && s[i] <= '9'){\n res *= 10;\n res += s[i] - '0';\n i++;\n }\n ts.push_back({res, 0});\n i--;\n }\n else ts.push_back({0, s[i]});\n }\n stack<pair<int,int>> ops;\n vector<pair<int,int>> rpn;\n for(auto &t : ts){\n if(t.second == 0) rpn.push_back(t);\n else if(t.second == '+' || t.second == '-'){\n while(!ops.empty() && (ops.top().second == '+' || ops.top().second == '-')){\n rpn.push_back(ops.top());\n ops.pop();\n }\n ops.push(t);\n }\n else if(t.second == '(')ops.push(t);\n else{\n while(!ops.empty() && ops.top().second != '('){\n rpn.push_back(ops.top());\n ops.pop();\n }\n ops.pop();\n }\n }\n while(!ops.empty()){\n rpn.push_back(ops.top());ops.pop();\n }\n stack<int> o;\n\n\n for(auto &[n,t] :rpn){\n if(t == 0) o.push(n);\n else{\n int op2 = o.top(); o.pop();\n int op1 = o.top(); o.pop();\n if(t == '+') o.push(op1 + op2);\n else o.push(op1 - op2);\n }\n }\n return o.top();\n\n }\n\n};",
"memory": "21556"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n vector<pair<int,int>> ts;\n for(int i = 0;i < s.size();i++){\n if(s[i] == ' ')continue;\n else if(s[i] == '-' && (i == 0 || ts.back().second == '(' )){\n ts.push_back({0,0});\n ts.push_back({0,'-'});\n }\n else if(s[i] >= '0' && s[i] <= '9'){\n int res = 0;\n while(i < s.size() && s[i] >= '0' && s[i] <= '9'){\n res *= 10;\n res += s[i] - '0';\n i++;\n }\n ts.push_back({res, 0});\n i--;\n }\n else ts.push_back({0, s[i]});\n }\n stack<pair<int,int>> ops;\n vector<pair<int,int>> rpn;\n for(auto &t : ts){\n if(t.second == 0) rpn.push_back(t);\n else if(t.second == '+' || t.second == '-'){\n while(!ops.empty() && (ops.top().second == '+' || ops.top().second == '-')){\n rpn.push_back(ops.top());\n ops.pop();\n }\n ops.push(t);\n }\n else if(t.second == '(')ops.push(t);\n else{\n while(!ops.empty() && ops.top().second != '('){\n rpn.push_back(ops.top());\n ops.pop();\n }\n ops.pop();\n }\n }\n while(!ops.empty()){\n rpn.push_back(ops.top());ops.pop();\n }\n stack<int> o;\n\n\n for(auto &[n,t] :rpn){\n if(t == 0) o.push(n);\n else{\n int op2 = o.top(); o.pop();\n int op1 = o.top(); o.pop();\n if(t == '+') o.push(op1 + op2);\n else o.push(op1 - op2);\n }\n }\n return o.top();\n\n }\n\n};",
"memory": "21556"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "#include <iostream>\n#include <stack>\n#include <string>\n#include <vector>\nusing namespace std;\nclass Solution {\npublic:\n vector<string> createTokens(string s) {\n vector<string> tokens;\n int start = 0, end = 0;\n if (s[0] != '+' && s[0] != '-') {\n tokens.push_back(\"+\");\n }\n\n while (end < s.length()) {\n if (s[start] == ' ') {\n start++;\n end++;\n }\n else if (s[start] == '+' || s[start] == '-' || s[start] == '(' || s[start] == ')') {\n tokens.push_back({s[start]});\n start++;\n end++;\n }\n else if (s[end] == '+' || s[end] == '-' || s[end] == '(' || s[end] == ')' || s[end] == ' ') {\n if (tokens.back() == \"+\") {\n tokens.pop_back();\n tokens.push_back(\"+\" + s.substr(start, end - start));\n }\n else if (tokens.back() == \"-\") {\n tokens.pop_back();\n tokens.push_back(\"-\" + s.substr(start, end - start));\n }\n else {\n tokens.push_back(\"+\" + s.substr(start, end - start));\n }\n start = end;\n }\n else {\n end++;\n }\n }\n if (start < s.length()) {\n if (tokens.back() == \"+\") {\n tokens.pop_back();\n tokens.push_back(\"+\" + s.substr(start, end - start));\n }\n else if (tokens.back() == \"-\") {\n tokens.pop_back();\n tokens.push_back(\"-\" + s.substr(start, end - start));\n }\n else {\n tokens.push_back(\"+\" + s.substr(start, end - start));\n }\n }\n\n return tokens;\n }\n\n int calculate(string s) {\n vector<string> tokens = createTokens(s);\n\n for (auto token : tokens) {\n cout << token << \", \";\n }\n cout << \"\\n\";\n\n stack<bool> isAdd;\n isAdd.push(true);\n int sum = 0;\n for (string token : tokens) {\n bool isToggle;\n if (token.length() > 1) {\n sum += isAdd.top() ? stoi(token) : 0 - stoi(token);\n }\n else if (token == \"+\") {\n isToggle = false;\n }\n else if (token == \"-\") {\n isToggle = true;\n }\n else if (token == \"(\") {\n isAdd.push(isAdd.top() ^ isToggle);\n }\n else if (token == \")\") {\n isAdd.pop();\n }\n }\n\n return sum;\n }\n};",
"memory": "22493"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<string> st;\n int n = s.size();\n for(int i = 0; i < n; i++) {\n if(s[i] == ' ') continue;\n else if(s[i] == '(') st.push(\"(\");\n else if(s[i] == '+') st.push(\"+\");\n else if(s[i] == '-') st.push(\"-\");\n else if(isdigit(s[i])) {\n int j = i + 1;\n while(j < n && isdigit(s[j])) j++;\n st.push(s.substr(i, j - i));\n i = j - 1;\n }\n else {\n double val = 0, lastAdd = 0;\n while(!(st.top() == \"(\")) {\n string str = st.top();\n st.pop();\n if(str != \"+\" && str != \"-\") {\n val += stoi(str);\n lastAdd = stoi(str);\n }\n else if(str == \"-\") val -= (2*lastAdd);\n }\n st.pop();\n st.push(to_string(val));\n }\n }\n\n double val = 0, lastAdd = 0;\n while(!st.empty()) {\n string str = st.top();\n st.pop();\n if(str != \"+\" && str != \"-\") {\n val += stoi(str);\n lastAdd = stoi(str);\n }\n else if(str == \"-\") val -= (2*lastAdd);\n }\n\n return val;\n }\n};",
"memory": "22493"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<string>st;\n int n=s.length();\n cout<<n<<endl;\n for(int i=0;i<n;i++){\n if(s[i]==' ') continue;\n else if(s[i]=='('){\n st.push(\"(\");\n }\n else if(s[i]=='+') st.push(\"+\");\n else if(s[i]=='-') st.push(\"-\");\n else if(s[i]!=')'){\n string temp;\n int j=i;\n while(j<n&&s[j]!=')'&&s[j]!='('&&s[j]!='+'&&s[j]!='-'){\n if(s[j]==' ') j++;\n else{\n temp.push_back(s[j]);\n j++;\n }\n }\n i=j-1;\n st.push(temp);\n }\n else{\n int ans=0;\n while(st.size()>0&&st.top()!=\"(\"){\n string temp=st.top();\n st.pop();\n string ans1=st.top();\n st.pop();\n if(ans1==\"(\"){\n ans+=stoi(temp);\n break;\n }\n else{\n if(ans1==\"+\"){\n ans+=stoi(temp);\n }\n else{\n ans-=stoi(temp);\n }\n }\n }\n if(st.size()>0&&st.top()==\"(\") st.pop();\n st.push(to_string(ans));\n }\n }\n int ans=0;\n while(st.size()>0){\n if(st.size()<2){\n string ans2=st.top();\n ans+=stoi(ans2);\n st.pop();\n }\n else{\n string ans1=st.top();\n st.pop();\n string temp=st.top();\n st.pop();\n if(temp==\"+\"){\n ans+=stoi(ans1);\n }\n else{\n ans-=stoi(ans1);\n }\n }\n }\n // while(st.size()>0){\n // string p=st.top();\n // cout<<p<<endl;\n // st.pop();\n // }\n return ans;\n }\n};",
"memory": "23431"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n bool isOperator(char c) {\n return c == '*' || c == '+' || c == '-' || c == '/';\n }\n\n static int eval12(int a, int b, string i) {\n if (i == \"+\")\n return a + b;\n if (i == \"*\")\n return a * b;\n if (i == \"-\")\n return a - b;\n if (i == \"/\")\n return a / b;\n\n return 0;\n }\n void performOperation(stack<string> &st, string temp) {\n if (st.empty() || st.top() == \"(\") {\n st.push(temp);\n } else if (isOperator(st.top()[0])) {\n char oper = st.top()[0];\n st.pop();\n\n // cout<<oper<<endl;\n\n if (oper == '-' && (st.empty() || st.top() == \"(\")) {\n st.push(to_string(eval12(0, stoi(temp), string(1, oper))));\n\n } else {\n string t1 = st.top();\n st.pop();\n\n // cout<<t1<<\" \"<<temp;\n\n st.push(\n to_string(eval12(stoi(t1), stoi(temp), string(1, oper))));\n }\n }\n }\n\n int calculate(string s) {\n int n = s.size();\n stack<string> st;\n int i = 0;\n\n while (i < n) {\n if (s[i] == ' ') {\n i++;\n continue;\n }\n if (s[i] == '(' || isOperator(s[i])) {\n st.push(string(1, s[i]));\n i++;\n } else if (s[i] == ')') {\n string t = st.top();\n st.pop();\n st.pop();\n cout << t << endl;\n\n performOperation(st, t);\n\n // st.push(t);\n i++;\n }\n\n else {\n string temp = \"\";\n\n while (i < n && (s[i] >= '0' && s[i] <= '9')) {\n temp += s[i++];\n }\n\n if (st.empty() || st.top() == \"(\") {\n st.push(temp);\n } else if (isOperator(st.top()[0])) {\n char oper = st.top()[0];\n st.pop();\n\n // cout<<oper<<endl;\n\n if (oper == '-' && (st.empty() || st.top() == \"(\")) {\n cout<<to_string(eval12(0, stoi(temp), string(1,oper)))<<\"hello\"<<endl;\n st.push(\n to_string(eval12(0, stoi(temp), string(1,oper))));\n\n } else {\n string t1 = st.top();\n st.pop();\n\n // cout<<t1<<\" \"<<temp;\n\n st.push(to_string(\n eval12(stoi(t1), stoi(temp), string(1, oper))));\n }\n }\n }\n }\n\n return stoi(st.top());\n }\n};",
"memory": "23431"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n // Function to evaluate a primary factor (number or expression in\n // parentheses)\n double evalFactor(std::stringstream& ss) {\n ss >> std::ws; // Skip any whitespace\n char c = ss.peek();\n\n // Handle unary plus and minus\n if (c == '+' || c == '-') {\n ss.get(); // consume the operator\n double factor = evalFactor(ss); // evaluate the next factor\n return (c == '-') ? -factor : factor;\n } else if (c == '(') {\n ss.get(); // consume '('\n double result = evalExpression(ss);\n ss >> std::ws; // Skip any whitespace\n if (ss.get() != ')')\n throw std::runtime_error(\"Expected closing parenthesis\");\n return result;\n } else if (std::isdigit(c) || c == '.') {\n double result;\n ss >> result; // read the number\n return result;\n } else {\n throw std::runtime_error(\n \"Unexpected character encountered in evalFactor\");\n }\n }\n\n // Function to evaluate terms with multiplication, division, and modulus\n double evalTerm(std::stringstream& ss) {\n double result = evalFactor(ss);\n\n while (true) {\n ss >> std::ws; // Skip any whitespace\n char c = ss.peek();\n if (c == '*' || c == '/' || c == '%') {\n char op = ss.get();\n double rhs = evalFactor(ss);\n if (op == '*')\n result *= rhs;\n else if (op == '/') {\n if (rhs == 0)\n throw std::runtime_error(\"Division by zero\");\n result /= rhs;\n } else if (op == '%') {\n if (rhs == 0)\n throw std::runtime_error(\"Division by zero\");\n result = static_cast<int>(result) % static_cast<int>(rhs);\n }\n } else {\n break;\n }\n }\n\n return result;\n }\n\n // Function to evaluate the entire expression with addition and subtraction\n double evalExpression(std::stringstream& ss) {\n double result = evalTerm(ss);\n\n while (true) {\n ss >> std::ws; // Skip any whitespace\n char c = ss.peek();\n if (c == '+' || c == '-') {\n char op = ss.get();\n double rhs = evalTerm(ss);\n if (op == '+')\n result += rhs;\n else if (op == '-')\n result -= rhs;\n } else {\n break;\n }\n }\n\n return result;\n }\n\n // Wrapper function to evaluate a string expression\n double eval(const std::string& expression) {\n std::stringstream ss(expression);\n return evalExpression(ss);\n }\n double calculate(string s) {\n double result = eval(s);\n return result;\n }\n};",
"memory": "24368"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<string> memo;\n\n for (int i = 0; i < s.size(); ++i) {\n char currChar = s[i];\n if (currChar == ')'){\n cleanStack(memo);\n }\n else{\n if (currChar == ' '){\n continue;\n }\n // cout << \"Added: \" << currChar << endl;\n memo.push(string() + currChar);\n }\n }\n\n cleanStack(memo);\n // cout << \"End of Algo. Stack Top: \" << memo.top() << endl;\n return stoi(memo.top());\n }\n\n void cleanStack(stack<string>& memo){\n int currSum = 0;\n int localSum = 0;\n int power = 0;\n\n while(!memo.empty() && memo.top() != \"(\"){\n string currStr = memo.top();\n memo.pop();\n\n if (currStr == \"+\" || currStr == \"-\"){\n \n localSum += currStr == \"-\" ? currSum * -1 : currSum;\n // cout << \"Adding to Local Sum... Curr Sum: \" << currSum << \", Local Sum: \" << localSum << endl;\n currSum = 0;\n power = 0;\n } else {\n int ogCurrSum = currSum;\n currSum += stoi(currStr) * pow(10, power);\n power++;\n // cout << \"Adding to Curr Sum... Was \" << ogCurrSum << \", Now is: \" << currSum << \", Power++: \" << power << endl; \n }\n }\n\n localSum += currSum;\n // cout << \"Adding to Local Sum... Curr Sum: \" << currSum << \", Local Sum: \" << localSum << endl;\n\n if (!memo.empty()) memo.pop();\n memo.push(to_string(localSum)); \n }\n};",
"memory": "24368"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n string str=\"\";\n for(int i=0;i<s.size();i++){\n if(s[i]!=' ')\n str.push_back(s[i]);\n }\n s=str;\n stack<string> st;\n s=\"(\"+s+\")\";\n string t=\"\";\n for(int i=0;i<s.size();i++){\n if(s[i]=='('||s[i]=='+'||s[i]=='-'){\n string k=\"\";\n k.push_back(s[i]);\n if(t!=\"\"){\n st.push(t);\n t=\"\";\n }\n st.push(k);\n }else if(s[i]>='0'&&s[i]<='9'){\n t.push_back(s[i]);\n }else{\n int ans=0;\n if(t!=\"\"){\n st.push(t);\n t=\"\";\n }\n // string srk=\"\";\n // while(!st.empty()){\n // srk+=st.top();\n // st.pop();\n // }\n // reverse(srk.begin(),srk.end());\n // cout<<srk<<endl;\n while(st.top()!=\"(\"){\n\n string s1=st.top();\n st.pop();\n if(st.top()==\"+\"||st.top()==\"-\"){\n s1=st.top()+s1;\n st.pop();\n }\n ans+=stoi(s1);\n }\n st.pop();\n if(ans<0&&st.size()>=1&&st.top()==\"-\"){\n st.pop();\n st.push(\"+\");\n st.push(to_string(abs(ans)));\n }else if(ans<0&&st.size()>=1&&st.top()==\"+\"){\n st.pop();\n st.push(\"-\");\n st.push(to_string(abs(ans)));\n\n }\n else{\n st.push(to_string(ans));\n }\n \n }\n }\n \n return stoi(st.top());\n // return 10;\n \n }\n};",
"memory": "25306"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n\n enum class CalcType\n {\n Number,\n Plus,\n Minus,\n OpenBracket,\n CloseBracket\n };\n\n struct CalcOp\n {\n CalcType type;\n int value;\n };\n\n vector<CalcOp> opList;\n\n void printOps()\n {\n for (int i = 0; i < opList.size(); ++i)\n {\n CalcOp& op = opList[i];\n if (op.type == CalcType::Plus) printf(\" Plus\\n\");\n if (op.type == CalcType::Minus) printf(\" Minus\\n\");\n if (op.type == CalcType::Number) printf(\" Number: %d\\n\", op.value);\n if (op.type == CalcType::OpenBracket) printf(\" Open Bracket\\n\");\n if (op.type == CalcType::CloseBracket) printf(\" Close Bracket\\n\");\n }\n }\n\n int executeOps(vector<CalcOp> ops)\n {\n bool addState = false;\n bool subState = false;\n int tmpNum = 0;\n\n for (int i = 0; i < ops.size(); ++i)\n {\n CalcOp& op = ops[i];\n\n if (op.type == CalcType::Plus)\n {\n //printf(\"Add encounted.\\n\");\n addState = true;\n subState = false;\n }\n\n if (op.type == CalcType::Minus)\n {\n //printf(\"Minus encounted.\\n\");\n addState = false;\n subState = true;\n }\n\n if (op.type == CalcType::Number)\n {\n //printf(\"Number encounted %d\\n\", op.value);\n\n if (addState)\n {\n //printf(\"Adding %d + %d\\n\", tmpNum, op.value);\n tmpNum += op.value;\n addState = false;\n }\n else if (subState)\n {\n //printf(\"Subtracting %d - %d\\n\", tmpNum, op.value);\n tmpNum -= op.value;\n subState = false;\n \n }\n else \n {\n tmpNum = op.value;\n //printf(\"Setting tmp: %d\\n\", tmpNum);\n }\n }\n }\n\n return tmpNum;\n }\n\n // Walks backward in the list and processes everything up until\n // an opening bracket.\n void processBracketClose()\n {\n vector<CalcOp> bracketOps;\n\n int opIndex = opList.size() - 1;\n for (; opIndex >= 0; opIndex--)\n {\n CalcOp& op = opList[opIndex];\n\n if (op.type == CalcType::OpenBracket)\n {\n break;\n } \n else \n {\n bracketOps.insert(bracketOps.begin(), op);\n }\n }\n\n //printf(\"Ops before erase:\\n\");\n //printOps();\n opList.erase(opList.begin() + opIndex, opList.end());\n int result = executeOps(bracketOps);\n //printf(\"Ops after erase:\\n\");\n //printOps();\n\n CalcOp newOp;\n newOp.type = CalcType::Number;\n newOp.value = result;\n opList.push_back(newOp);\n\n //printf(\"Finished bracket pushing result %d\\n\", result);\n }\n\n int calculate(string s) \n {\n string pendingNumber = \"\";\n bool collectingNumber = false;\n\n for (int i = 0; i < s.length(); ++i)\n {\n bool nonNumber = false;\n bool closingBracket = false;\n bool addOp = false;\n CalcOp opToAdd;\n\n char c = s[i];\n if (c == ' ')\n {\n nonNumber = true;\n }\n else if (c == '+')\n {\n opToAdd.type = CalcType::Plus;\n opToAdd.value = 0;\n addOp = true;\n nonNumber = true;\n }\n else if (c == '-')\n {\n opToAdd.type = CalcType::Minus;\n opToAdd.value = 0;\n addOp = true;\n nonNumber = true;\n }\n else if (c == '(')\n {\n opToAdd.type = CalcType::OpenBracket;\n opToAdd.value = 0;\n addOp = true;\n nonNumber = true;\n }\n else if (c == ')')\n {\n opToAdd.type = CalcType::CloseBracket;\n opToAdd.value = 0;\n addOp = true;\n nonNumber = true;\n closingBracket = true;\n }\n else \n {\n nonNumber = false;\n collectingNumber = true;\n pendingNumber += c;\n }\n\n if (collectingNumber && nonNumber)\n {\n CalcOp newOp;\n newOp.type = CalcType::Number;\n newOp.value = std::stoi(pendingNumber);\n opList.push_back(newOp);\n //printf(\"Collected number: %d\\n\", newOp.value);\n collectingNumber = false;\n pendingNumber = \"\";\n }\n\n if (addOp)\n {\n opList.push_back(opToAdd);\n }\n\n if (closingBracket)\n {\n processBracketClose();\n }\n } \n\n if (pendingNumber != \"\")\n {\n CalcOp newOp;\n newOp.type = CalcType::Number;\n newOp.value = std::stoi(pendingNumber);\n opList.push_back(newOp);\n }\n\n return executeOps(opList);\n }\n};",
"memory": "25306"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n \n void solve(stack<string>&st){\n string a =\"\";\n while(!st.empty() && st.top()[0] != '('){\n a += st.top();\n st.pop();\n }\n\n if(!st.empty()){\n st.pop();\n }\n reverse(a.begin(),a.end());\n int i=0;\n int sum = 0;\n bool sign = true; // plus\n int plus = 0;\n int minus = 0;\n while(i<a.length() && (a[i] == '+' || a[i] == '-')){\n if(a[i] == '+'){\n plus ++;\n }\n else{\n minus++;\n }\n i++;\n }\n if(minus%2 == 0){\n sign = true;\n }\n else{\n sign = false;\n }\n while(i<a.length()){\n string temp = \"\";\n while(i<a.length() && a[i] != '+' && a[i] != '-'){\n temp.push_back(a[i]);\n i++;\n }\n int num = stoi(temp);\n if(sign == true){\n sum += num;\n }\n else{\n sum -= num;\n }\n int plus = 0;\n int minus = 0;\n while(i<a.length() && (a[i] == '+' || a[i] == '-')){\n if(a[i] == '+'){\n plus ++;\n }\n else{\n minus++;\n }\n i++;\n }\n if(minus%2 == 0){\n sign = true;\n }\n else{\n sign = false;\n }\n }\n if(sum < 0){\n string b=\"-\";\n st.push(b);\n b = to_string(abs(sum));\n reverse(b.begin(),b.end());\n st.push(b);\n }\n else if(sum>=0){\n string b=\"\";\n b = to_string(sum);\n reverse(b.begin(),b.end());\n st.push(b);\n }\n\n }\n int calculate(string s) {\n stack<string>st;\n for(int i=0; i<s.length(); i++){\n while(i<s.length() && s[i] != ')'){\n while(i<s.length() && s[i] == ' '){\n i++;\n }\n string a =\"\";\n a.push_back(s[i]);\n st.push(a);\n i++;\n }\n solve(st);\n }\n if(st.empty()){\n return 0;\n }\n else{\n solve(st);\n string ans = st.top();\n st.pop();\n reverse(ans.begin(),ans.end());\n int finalans = stoi(ans);\n if(!st.empty() && st.top()[0] == '-'){\n finalans = finalans*(-1);\n }\n return finalans;\n }\n }\n};",
"memory": "26243"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n \n void solve(stack<string>&st){\n string a =\"\";\n while(!st.empty() && st.top()[0] != '('){\n a += st.top();\n st.pop();\n }\n\n if(!st.empty()){\n st.pop();\n }\n reverse(a.begin(),a.end());\n int i=0;\n int sum = 0;\n bool sign = true; // plus\n int plus = 0;\n int minus = 0;\n while(i<a.length() && (a[i] == '+' || a[i] == '-')){\n if(a[i] == '+'){\n plus ++;\n }\n else{\n minus++;\n }\n i++;\n }\n if(minus%2 == 0){\n sign = true;\n }\n else{\n sign = false;\n }\n while(i<a.length()){\n string temp = \"\";\n while(i<a.length() && a[i] != '+' && a[i] != '-'){\n temp.push_back(a[i]);\n i++;\n }\n int num = stoi(temp);\n if(sign == true){\n sum += num;\n }\n else{\n sum -= num;\n }\n int plus = 0;\n int minus = 0;\n while(i<a.length() && (a[i] == '+' || a[i] == '-')){\n if(a[i] == '+'){\n plus ++;\n }\n else{\n minus++;\n }\n i++;\n }\n if(minus%2 == 0){\n sign = true;\n }\n else{\n sign = false;\n }\n }\n if(sum < 0){\n string b=\"-\";\n st.push(b);\n b = to_string(abs(sum));\n reverse(b.begin(),b.end());\n st.push(b);\n }\n else if(sum>=0){\n string b=\"\";\n b = to_string(sum);\n reverse(b.begin(),b.end());\n st.push(b);\n }\n\n }\n int calculate(string s) {\n stack<string>st;\n for(int i=0; i<s.length(); i++){\n while(i<s.length() && s[i] != ')'){\n while(i<s.length() && s[i] == ' '){\n i++;\n }\n string a =\"\";\n a.push_back(s[i]);\n st.push(a);\n i++;\n }\n solve(st);\n }\n if(st.empty()){\n return 0;\n }\n else{\n solve(st);\n string ans = st.top();\n st.pop();\n reverse(ans.begin(),ans.end());\n int finalans = stoi(ans);\n if(!st.empty() && st.top()[0] == '-'){\n finalans = finalans*(-1);\n }\n return finalans;\n }\n }\n};",
"memory": "26243"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int f(string s){\n // cout<<s<<\" \";\n string res=\"\";\n int n=s.size();\n int ans=0,j=0;\n while(j<n){\n \n string res=\"\";\n if(j<=n-2){\n if(isdigit(s[j])==false && isdigit(s[j+1])==false){\n if((s[j]=='+' && s[j+1]=='+') || (s[j]=='-' && s[j+1]=='-') ){\n res+='+';\n }else{\n res+='-';\n }\n j+=2;\n }else{\n res+=s[j];\n j++;\n }\n }else{\n res+=s[j];\n j++;\n }\n \n \n while(j<n && (s[j]!='+' && s[j]!='-')){\n \n res+=s[j];\n j++;\n }\n cout<<res<<\" \";\n int num=stoi(res);\n // cout<<res<<\" \";\n ans+=num;\n \n }\n return ans;\n \n }\n\n\n\n\n\n\n int calculate(string s1) {\n string s=\"\";\n for(auto it:s1){\n if(it==' ')continue;\n s+=it;\n }\n // cout<<s;\n stack<string>st;\n int n=s.size();\n int j=n-1;\n\n while(j>=0){\n if(s[j]==')'){\n \n st.push(\")\");\n j--;\n }else if(s[j]=='('){\n string res=\"\";\n while(!st.empty() && st.top()!=\")\"){\n res+=st.top();\n st.pop();\n }\n st.pop();\n int x=f(res);\n // cout<<res<<\" \";\n // cout<<res<<\" \";\n // cout<<x<<\" \";\n st.push(to_string(x));\n // cout<<st.top();\n j--;\n }else{\n string ac=\"\";\n ac+=s[j];\n // cout<<ac<<\" \";\n st.push(ac);\n j--;\n }\n }\n \n string res2=\"\";\n while(!st.empty()){\n res2+=st.top();\n st.pop();\n }\n return f(res2);\n }\n};",
"memory": "27181"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "#include <iostream>\n#include <string>\n#include <stack>\nusing namespace std;\nclass Solution {\npublic:\n int calculate(string s) {\n // All The Calculations are Pushed And Done On A Stack\n stack<string> stack;\n bool preparing_for_calculation = false;\n bool is_operator_ready = false;\n bool negative_val = false;\n\n // Example String: s = \"( 1+(10+10+2)-3)+(6+8)\"\n for (int i = 0; i < s.size(); i++) {\n // Special Case Only For The \"-\" Operator. For Reliability Just Check If The Previous In Stack Is A Number.\n if (stack.empty() && s[i] == '-') {\n negative_val = true;\n stack.push(string(1, s[i]));\n continue;\n }\n // Ensures Multiple Integer Digit Get Saved In The Same Stack Container\n if ((i != 0 && isdigit(s[i]) && isdigit(s[i - 1]))|| negative_val ==true && isdigit(s[i])) {\n // Update The Last Stack Value To Add The Newest Character\n string temp_string = stack.top();\n stack.pop();\n temp_string += s[i];\n stack.push(temp_string);\n negative_val = false;\n continue;\n }\n // Skip Over All Spaces Manually To Save Computation Time\n if (s[i] == ' ') {\n continue;\n }\n // Adds Up While Traveling The Stack\n if ((s[i] == '+' || s[i] == '-') && preparing_for_calculation == true && is_operator_ready == true) {\n int temp_val1 = stoi(stack.top());// Retrieving the Second Value\n stack.pop();\n string Operator = string(stack.top());// Retrieving Operator.\n stack.pop();\n int temp_val2 = stoi(stack.top()); // Retrieving First Value\n stack.pop();\n string result = to_string(doing_math(temp_val2, temp_val1, Operator));\n stack.push(result); // Pushing In The Result \n stack.push(string(1, s[i]));// Pushing In The Operator.\n continue;\n }\n\n if (isdigit(s[i])) {\n stack.push(string(1,s[i]));\n preparing_for_calculation = true;\n continue;\n }\n // The Values Inside () can either be one value or (num+num).\n if (s[i] == ')') {\n string result = \"\";\n int first_value = stoi(stack.top());\n int second_value = 0;\n stack.pop();\n //Start Popping Stacks Until '(' is reached\n while (stack.top() != \"(\") {\n if (result != \"\") {\n first_value = stoi(result);\n }\n string Operator = stack.top();\n stack.pop();\n if (stack.top() == \"(\") {\n result = to_string(doing_math(second_value, first_value, Operator));\n continue;\n }\n int second_value = stoi(stack.top());\n stack.pop();\n result = to_string(doing_math(second_value, first_value, Operator));\n continue;\n }\n if (result == \"\") {\n result = to_string(first_value);\n }\n\n stack.pop();// For The \"(\" Bracket.\n // Checking If Operator Outside Is Negative.\n if (!stack.empty() && stack.top() == \"-\") {\n if (result[0] == '-') {\n result = result.substr(1);\n }\n else {\n result = \"-\" + result;\n }\n stack.pop();// Removing The Negative Value\n if (stack.size() > 0) {\n stack.push(\"+\");\n }\n stack.push(result);\n }\n else {\n stack.push(result);// Pushes The Actual Value In\n }\n is_operator_ready = false;\n continue;\n }\n if (s[i] == '(') {\n preparing_for_calculation = false; // Reset The Flag\n is_operator_ready = false;\n negative_val = false;\n stack.push(string(1, s[i]));\n continue;\n }\n else {\n stack.push(string(1,s[i])); // Adds Up The Operators \"+\" , \"-\".\n is_operator_ready = true;\n }\n\n }\n // Add Up Any Remaining Values In The Stack\n int result = stoi(stack.top());\n stack.pop();\n while (!stack.empty()) {\n string Operator = stack.top();\n stack.pop();\n int second_val = 0;\n if (!stack.empty()) {\n second_val = stoi(stack.top());\n stack.pop();\n }\n result = doing_math(second_val, result, Operator);\n \n }\n\n return result;\n }\n // Does The Actual Math Part When Called By calculate Function\n int doing_math(int num1, int num2, string Operator) {\n if (Operator == \"+\") {\n return num1 + num2;\n }\n if (Operator == \"-\") {\n return num1 - num2;\n }\n cout << \"False Operators Found\";\n return 0;\n }\n};",
"memory": "27181"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "#include <iostream>\n#include <string>\n#include <stack>\nusing namespace std;\nclass Solution {\npublic:\n int calculate(string s) {\n // All The Calculations are Pushed And Done On A Stack\n stack<string> stack;\n bool preparing_for_calculation = false;\n bool is_operator_ready = false;\n bool negative_val = false;\n\n // Example String: s = \"( 1+(10+10+2)-3)+(6+8)\"\n for (int i = 0; i < s.size(); i++) {\n // Special Case Only For The \"-\" Operator. For Reliability Just Check If The Previous In Stack Is A Number.\n if (stack.empty() && s[i] == '-') {\n negative_val = true;\n stack.push(string(1, s[i]));\n continue;\n }\n // Ensures Multiple Integer Digit Get Saved In The Same Stack Container\n if ((i != 0 && isdigit(s[i]) && isdigit(s[i - 1]))|| negative_val ==true && isdigit(s[i])) {\n // Update The Last Stack Value To Add The Newest Character\n string temp_string = stack.top();\n stack.pop();\n temp_string += s[i];\n stack.push(temp_string);\n negative_val = false;\n continue;\n }\n // Skip Over All Spaces Manually To Save Computation Time\n if (s[i] == ' ') {\n continue;\n }\n // Adds Up While Traveling The Stack\n if ((s[i] == '+' || s[i] == '-') && preparing_for_calculation == true && is_operator_ready == true) {\n int temp_val1 = stoi(stack.top());// Retrieving the Second Value\n stack.pop();\n string Operator = string(stack.top());// Retrieving Operator.\n stack.pop();\n int temp_val2 = stoi(stack.top()); // Retrieving First Value\n stack.pop();\n string result = to_string(doing_math(temp_val2, temp_val1, Operator));\n stack.push(result); // Pushing In The Result \n stack.push(string(1, s[i]));// Pushing In The Operator.\n continue;\n }\n\n if (isdigit(s[i])) {\n stack.push(string(1,s[i]));\n preparing_for_calculation = true;\n continue;\n }\n // The Values Inside () can either be one value or (num+num).\n if (s[i] == ')') {\n string result = \"\";\n int first_value = stoi(stack.top());\n int second_value = 0;\n stack.pop();\n //Start Popping Stacks Until '(' is reached\n while (stack.top() != \"(\") {\n if (result != \"\") {\n first_value = stoi(result);\n }\n string Operator = stack.top();\n stack.pop();\n if (stack.top() == \"(\") {\n result = to_string(doing_math(second_value, first_value, Operator));\n continue;\n }\n int second_value = stoi(stack.top());\n stack.pop();\n result = to_string(doing_math(second_value, first_value, Operator));\n continue;\n }\n if (result == \"\") {\n result = to_string(first_value);\n }\n\n stack.pop();// For The \"(\" Bracket.\n // Checking If Operator Outside Is Negative.\n if (!stack.empty() && stack.top() == \"-\") {\n if (result[0] == '-') {\n result = result.substr(1);\n }\n else {\n result = \"-\" + result;\n }\n stack.pop();// Removing The Negative Value\n if (stack.size() > 0) {\n stack.push(\"+\");\n }\n stack.push(result);\n }\n else {\n stack.push(result);// Pushes The Actual Value In\n }\n is_operator_ready = false;\n continue;\n }\n if (s[i] == '(') {\n preparing_for_calculation = false; // Reset The Flag\n is_operator_ready = false;\n negative_val = false;\n stack.push(string(1, s[i]));\n continue;\n }\n else {\n stack.push(string(1,s[i])); // Adds Up The Operators \"+\" , \"-\".\n is_operator_ready = true;\n }\n\n }\n // Add Up Any Remaining Values In The Stack\n int result = stoi(stack.top());\n stack.pop();\n while (!stack.empty()) {\n string Operator = stack.top();\n stack.pop();\n int second_val = 0;\n if (!stack.empty()) {\n second_val = stoi(stack.top());\n stack.pop();\n }\n result = doing_math(second_val, result, Operator);\n \n }\n\n return result;\n }\n // Does The Actual Math Part When Called By calculate Function\n int doing_math(int num1, int num2, string Operator) {\n if (Operator == \"+\") {\n return num1 + num2;\n }\n if (Operator == \"-\") {\n return num1 - num2;\n }\n cout << \"False Operators Found\";\n return 0;\n }\n};",
"memory": "28118"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "#include <iostream>\n#include <string>\n#include <stack>\nusing namespace std;\nclass Solution {\npublic:\n int calculate(string s) {\n // All The Calculations are Pushed And Done On A Stack\n stack<string> stack;\n bool preparing_for_calculation = false;\n bool is_operator_ready = false;\n bool negative_val = false;\n\n // Example String: s = \"( 1+(10+10+2)-3)+(6+8)\"\n for (int i = 0; i < s.size(); i++) {\n // Special Case Only For The \"-\" Operator. For Reliability Just Check If The Previous In Stack Is A Number.\n if (stack.empty() && s[i] == '-') {\n negative_val = true;\n stack.push(string(1, s[i]));\n continue;\n }\n // Ensures Multiple Integer Digit Get Saved In The Same Stack Container\n if ((i != 0 && isdigit(s[i]) && isdigit(s[i - 1]))|| negative_val ==true && isdigit(s[i])) {\n // Update The Last Stack Value To Add The Newest Character\n string temp_string = stack.top();\n stack.pop();\n temp_string += s[i];\n stack.push(temp_string);\n negative_val = false;\n continue;\n }\n // Skip Over All Spaces Manually To Save Computation Time\n if (s[i] == ' ') {\n continue;\n }\n // Adds Up While Traveling The Stack\n if ((s[i] == '+' || s[i] == '-') && preparing_for_calculation == true && is_operator_ready == true) {\n int temp_val1 = stoi(stack.top());// Retrieving the Second Value\n stack.pop();\n string Operator = string(stack.top());// Retrieving Operator.\n stack.pop();\n int temp_val2 = stoi(stack.top()); // Retrieving First Value\n stack.pop();\n string result = to_string(doing_math(temp_val2, temp_val1, Operator));\n stack.push(result); // Pushing In The Result \n stack.push(string(1, s[i]));// Pushing In The Operator.\n continue;\n }\n\n if (isdigit(s[i])) {\n stack.push(string(1,s[i]));\n preparing_for_calculation = true;\n continue;\n }\n // The Values Inside () can either be one value or (num+num).\n if (s[i] == ')') {\n string result = \"\";\n int first_value = stoi(stack.top());\n int second_value = 0;\n stack.pop();\n //Start Popping Stacks Until '(' is reached\n while (stack.top() != \"(\") {\n if (result != \"\") {\n first_value = stoi(result);\n }\n string Operator = stack.top();\n stack.pop();\n if (stack.top() == \"(\") {\n result = to_string(doing_math(second_value, first_value, Operator));\n continue;\n }\n int second_value = stoi(stack.top());\n stack.pop();\n result = to_string(doing_math(second_value, first_value, Operator));\n continue;\n }\n if (result == \"\") {\n result = to_string(first_value);\n }\n\n stack.pop();// For The \"(\" Bracket.\n // Checking If Operator Outside Is Negative.\n if (!stack.empty() && stack.top() == \"-\") {\n if (result[0] == '-') {\n result = result.substr(1);\n }\n else {\n result = \"-\" + result;\n }\n stack.pop();// Removing The Negative Value\n if (stack.size() > 0) {\n stack.push(\"+\");\n }\n stack.push(result);\n }\n else {\n stack.push(result);// Pushes The Actual Value In\n }\n is_operator_ready = false;\n continue;\n }\n if (s[i] == '(') {\n preparing_for_calculation = false; // Reset The Flag\n is_operator_ready = false;\n negative_val = false;\n stack.push(string(1, s[i]));\n continue;\n }\n else {\n stack.push(string(1,s[i])); // Adds Up The Operators \"+\" , \"-\".\n is_operator_ready = true;\n }\n\n }\n // Add Up Any Remaining Values In The Stack\n int result = stoi(stack.top());\n stack.pop();\n while (!stack.empty()) {\n string Operator = stack.top();\n stack.pop();\n int second_val = 0;\n if (!stack.empty()) {\n second_val = stoi(stack.top());\n stack.pop();\n }\n result = doing_math(second_val, result, Operator);\n \n }\n\n return result;\n }\n // Does The Actual Math Part When Called By calculate Function\n int doing_math(int num1, int num2, string Operator) {\n if (Operator == \"+\") {\n return num1 + num2;\n }\n if (Operator == \"-\") {\n return num1 - num2;\n }\n cout << \"False Operators Found\";\n return 0;\n }\n};",
"memory": "28118"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n int n = s.size();\n\n stack<string> st;\n string tmpNum = \"\";\n int cnt = 0;\n int tmpCnt = 0;\n int tmpA = 0;\n int tmpB = 0;\n bool isNeg = false;\n bool isBasket = false;\n char opera;\n\n for(int i = 0; i < n; i++)\n {\n if(s[i] != ' ')\n {\n if(s[i] == ')')\n {\n isBasket = false;\n isNeg = false;\n while(true)\n {\n tmpCnt = 0;\n tmpA = stoi(st.top());\n st.pop();\n\n if(st.top() == \"(\")\n {\n st.pop();\n if(st.size() && st.top() == \"-\")\n {\n isNeg = true;\n st.pop();\n }\n\n if(isNeg)\n st.push(to_string(-1 * tmpA));\n else\n st.push(to_string(tmpA));\n\n break;\n }\n\n opera = st.top()[0];\n st.pop();\n tmpB = stoi(st.top());\n st.pop();\n\n if(opera == '+')\n {\n tmpCnt = tmpA + tmpB;\n }\n else\n {\n tmpCnt = tmpB - tmpA;\n }\n\n printf(\"%d\\n\", tmpCnt);\n\n if(st.top() == \"(\")\n {\n st.pop();\n isBasket = true;\n if(st.size() && st.top() == \"-\")\n {\n isNeg = true;\n st.pop();\n }\n }\n\n if(isNeg)\n st.push(to_string(-1 * tmpCnt));\n else\n st.push(to_string(tmpCnt));\n\n printf(\"%d %c %d\\n\", tmpA, opera, tmpB);\n\n if(isBasket)\n break;\n }\n\n printf(\"%s\\n\", st.top().c_str());\n }\n else\n {\n if(s[i] == '+' || s[i] == '(')\n {\n st.push(string(1, s[i]));\n }\n else\n {\n tmpNum = \"\";\n isNeg = false;\n\n if(s[i] == '-')\n {\n isNeg = true;\n tmpNum += '-';\n i++;\n }\n\n while(s[i] >= '0' && s[i] <= '9' || s[i] == ' ')\n {\n if(s[i] != ' ')\n tmpNum += s[i];\n i++;\n\n if(i == n)\n break;\n }\n i--;\n if(isNeg /*&& tmpNum != \"-\"*/ && st.size() && st.top() != \"(\")\n st.push(\"+\");\n st.push(tmpNum);\n }\n }\n }\n }\n\n while(st.size() > 1)\n {\n tmpCnt = 0;\n tmpA = stoi(st.top());\n st.pop();\n opera = st.top()[0];\n st.pop();\n tmpB = stoi(st.top());\n st.pop();\n\n printf(\"%d %c %d\\n\", tmpA, opera, tmpB);\n\n if(opera == '+')\n {\n tmpCnt = tmpA + tmpB;\n }\n else\n {\n tmpCnt = tmpB - tmpA;\n }\n\n //if(!st.size())\n // break;\n\n st.push(to_string(tmpCnt));\n }\n\n return stoi(st.top());\n }\n};",
"memory": "29056"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n int n = s.size();\n\n stack<string> st;\n string tmpNum = \"\";\n int cnt = 0;\n int tmpCnt = 0;\n int tmpA = 0;\n int tmpB = 0;\n bool isNeg = false;\n bool isBasket = false;\n char opera;\n\n for(int i = 0; i < n; i++)\n {\n if(s[i] != ' ')\n {\n if(s[i] == ')')\n {\n isBasket = false;\n isNeg = false;\n while(true)\n {\n tmpCnt = 0;\n tmpA = stoi(st.top());\n st.pop();\n\n if(st.top() == \"(\")\n {\n st.pop();\n if(st.size() && st.top() == \"-\")\n {\n isNeg = true;\n st.pop();\n }\n\n if(isNeg)\n st.push(to_string(-1 * tmpA));\n else\n st.push(to_string(tmpA));\n\n break;\n }\n\n opera = st.top()[0];\n st.pop();\n tmpB = stoi(st.top());\n st.pop();\n\n if(opera == '+')\n {\n tmpCnt = tmpA + tmpB;\n }\n else\n {\n tmpCnt = tmpB - tmpA;\n }\n\n //printf(\"%d\\n\", tmpCnt);\n\n if(st.top() == \"(\")\n {\n st.pop();\n isBasket = true;\n if(st.size() && st.top() == \"-\")\n {\n isNeg = true;\n st.pop();\n }\n }\n\n if(isNeg)\n st.push(to_string(-1 * tmpCnt));\n else\n st.push(to_string(tmpCnt));\n\n //printf(\"%d %c %d\\n\", tmpA, opera, tmpB);\n\n if(isBasket)\n break;\n }\n\n //printf(\"%s\\n\", st.top().c_str());\n }\n else\n {\n if(s[i] == '+' || s[i] == '(')\n {\n st.push(string(1, s[i]));\n }\n else\n {\n tmpNum = \"\";\n isNeg = false;\n\n if(s[i] == '-')\n {\n isNeg = true;\n tmpNum += '-';\n i++;\n }\n\n while(s[i] >= '0' && s[i] <= '9' || s[i] == ' ')\n {\n if(s[i] != ' ')\n tmpNum += s[i];\n i++;\n\n if(i == n)\n break;\n }\n i--;\n if(isNeg /*&& tmpNum != \"-\"*/ && st.size() && st.top() != \"(\")\n st.push(\"+\");\n st.push(tmpNum);\n }\n }\n }\n }\n\n while(st.size() > 1)\n {\n tmpCnt = 0;\n tmpA = stoi(st.top());\n st.pop();\n opera = st.top()[0];\n st.pop();\n tmpB = stoi(st.top());\n st.pop();\n\n //printf(\"%d %c %d\\n\", tmpA, opera, tmpB);\n\n if(opera == '+')\n {\n tmpCnt = tmpA + tmpB;\n }\n else\n {\n tmpCnt = tmpB - tmpA;\n }\n\n //if(!st.size())\n // break;\n\n st.push(to_string(tmpCnt));\n }\n\n return stoi(st.top());\n }\n};",
"memory": "29056"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\n bool isdigit(char ch) {\n if(ch >= '0' && ch <= '9')\n return true;\n return false;\n }\n\n string convertCharToString(char ch) {\n string dummy = \"\";\n dummy = dummy + ch;\n return dummy;\n }\n\npublic:\n int calculate(string str) {\n str = \"(\" + str + \")\";\n reverse(str.begin(), str.end());\n stack<string> st;\n for(int i=0;i<str.length();i++) {\n // cout << \"currently processing char : \" << str[i] << endl;\n if(str[i] == ')' || isdigit(str[i]) || str[i] == '+' || str[i] == '-' ) {\n st.push(convertCharToString(str[i]));\n }\n else if (str[i] == '('){\n while(1) {\n int key;\n if(st.top() == \"-\") {\n key = 0;\n }\n else {\n key = stoi(st.top()); \n st.pop();\n while(st.top() != \")\" && st.top() != \"+\" && st.top() != \"-\") {\n key = key * 10 + stoi(st.top());\n st.pop();\n } \n }\n // cout << \"key popped is \" << key << endl;\n string op = st.top(); st.pop();\n if(op == \")\") {\n st.push(to_string(key));\n st.push(op);\n break;\n }\n int key2 = stoi(st.top()); st.pop();\n while(st.top()[0] != ')' && st.top()[0] != '+' && st.top()[0] != '-') {\n key2 = key2 * 10 + stoi(st.top());\n st.pop();\n }\n\n // cout << \"key2 popped is \" << key2 << endl;\n // cout << \"performing operation : \" << key << op << key2 << endl;\n int res = (op == \"+\") ? key + key2 : key - key2;\n st.push(to_string(res));\n }\n st.pop();\n }\n }\n return stoi(st.top());\n }\n};",
"memory": "29993"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\n int F(vector<string>& tokens, int& i, int multiplier, int& result) {\n if (i >= tokens.size())\n return 0;\n\n int sign = 1;\n\n for (; i < tokens.size(); i++) {\n string token = tokens[i];\n if (isdigit(token[0])) {\n result += multiplier * atoi(token.c_str());\n } else if (token == \"(\") {\n F(tokens, ++i, multiplier * sign, result);\n } else if (token == \")\") {\n return result;\n } else if (token == \"+\") {\n sign = 1;\n } else if (token == \"-\") {\n sign = -1;\n }\n }\n return 0;\n }\n\npublic:\n int calculate(string s) {\n\n // Step 1: Tokenization\n vector<string> tokens;\n string builder;\n for (char c : s) {\n if (isdigit(c)) {\n builder.push_back(c);\n } else {\n if (builder.size() > 0) {\n tokens.push_back(builder);\n builder.clear();\n }\n if (c != ' ') {\n builder.push_back(c);\n tokens.push_back(builder);\n builder.clear();\n }\n }\n }\n if (builder.size() > 0) {\n tokens.push_back(builder);\n builder.clear();\n }\n\n // Step 2: Calculation\n vector<int> multiplier = {1};\n int sign = 1;\n // int brackets = 0;\n int result = 0;\n int i = 0;\n for (auto& token : tokens) {\n if (token == \"+\") {\n sign = 1;\n } else if (token == \"-\") {\n sign = -1;\n } else if (token == \"(\"){\n multiplier.push_back(sign * multiplier.back());\n sign = 1;\n } else if (token == \")\"){\n multiplier.pop_back();\n } else {\n result += (sign * multiplier.back() * atoi(token.c_str()));\n }\n }\n\n return result;\n }\n};",
"memory": "29993"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n vector<char> oper_stack;\n vector<string> num_stack;\n vector<string> rpn;\n\n map<char, int> prec = {{'N', 4}, {'+', 2}, {'-', 2}, {'*', 3}, {'/', 3}};\n string stoi_tmp;\n bool unary_flag = true;\n\n for(const auto &c : s) {\n if(c == ' ' || c == '\\n') {\n continue;\n }\n\n if(isdigit(c)) {\n stoi_tmp = stoi_tmp + c;\n unary_flag = false;\n } else {\n if(unary_flag && c == '-') {\n oper_stack.push_back('N');\n continue;\n }\n if(stoi_tmp != \"\") {\n rpn.push_back(stoi_tmp);\n stoi_tmp = \"\";\n }\n if(oper_stack.size() != 0 && c != '(' && c != ')') {\n if(prec[c] <= prec[oper_stack.back()]) {\n while(oper_stack.size() != 0 && prec[c] <= prec[oper_stack.back()]) {\n if(oper_stack.back() == '(' || oper_stack.back() == ')') break;\n rpn.push_back(string(1, oper_stack.back()));\n oper_stack.pop_back();\n }\n } \n oper_stack.push_back(c);\n } else if(c == ')') {\n while(oper_stack.back() != '(') {\n rpn.push_back(string(1, oper_stack.back()));\n oper_stack.pop_back();\n }\n oper_stack.pop_back();\n if(oper_stack.size() != 0 && oper_stack.back() == 'N') {\n rpn.push_back(string(1, 'N'));\n oper_stack.pop_back();\n }\n } else {\n oper_stack.push_back(c);\n }\n if(c == '+' || c == '-' || c == '*' || c == '/' || c == '(') {\n unary_flag = true;\n } else {\n unary_flag = false;\n }\n }\n }\n \n\n if(stoi_tmp != \"\") {\n rpn.push_back(stoi_tmp);\n }\n\n while(oper_stack.size() != 0) {\n rpn.push_back(string(1, oper_stack.back()));\n oper_stack.pop_back();\n }\n\n vector<int> cal_stack;\n\n for(auto a : rpn) {\n cout << a << \" \";\n if(a != \"+\" && a != \"-\" && a != \"*\" && a != \"/\" && a != \"N\") {\n cal_stack.push_back(stoi(a));\n } else if(a == \"N\") {\n int tmp = -cal_stack.back();\n cal_stack.pop_back();\n cal_stack.push_back(tmp);\n } else {\n int suffix = cal_stack.back();\n cal_stack.pop_back();\n int prefix = cal_stack.back();\n cal_stack.pop_back();\n int pb;\n if(a == \"+\") {\n pb = prefix + suffix;\n } else if(a == \"-\") {\n pb = prefix - suffix;\n } else if(a == \"/\") {\n pb = prefix / suffix;\n } else if(a == \"*\"){\n pb = prefix * suffix;\n }\n cal_stack.push_back(pb);\n }\n }\n\n return cal_stack.back();\n }\n};",
"memory": "30931"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<char> st;\n vector<string> rpn;\n char ch;\n char prev = '(';\n\n for (int i = 0; i < s.length(); i++) {\n ch = s[i];\n if (ch == ' ') {\n continue;\n }\n\n switch (ch) {\n case '(':\n st.push(ch);\n break;\n case ')':\n st.pop();\n if (!st.empty() && st.top() != '(') {\n rpn.push_back(string(1, st.top()));\n st.pop();\n }\n break;\n case '+':\n st.push(ch);\n break;\n case '-':\n if (rpn.empty() || prev == '(') {\n rpn.push_back(\"0\");\n }\n st.push(ch);\n break;\n default:\n if (prev >= '0' && prev <= '9') {\n rpn.back() += ch;\n } else {\n rpn.push_back(string(1, ch));\n }\n\n if ((i == s.length() - 1 || (s[i + 1] < '0' || s[i + 1] > '9')) && \n (!st.empty() && st.top() != '(')) {\n rpn.push_back(string(1, st.top()));\n st.pop();\n }\n break;\n }\n\n prev = ch;\n }\n\n return evalRPN(rpn);\n }\n\n int evalRPN(vector<string>& tokens) {\n stack<int> operands;\n int num1 = 0;\n int num2 = 0;\n int result = 0;\n\n for (int i = 0; i < tokens.size(); i++) {\n if (tokens[i] == \"+\" || tokens[i] == \"-\") {\n num2 = operands.top();\n operands.pop();\n num1 = operands.top();\n operands.pop();\n\n switch (tokens[i][0]) {\n case '+':\n result = num1 + num2;\n break;\n case '-':\n result = num1 - num2;\n break;\n case '*':\n result = num1 * num2;\n break;\n case '/':\n result = num1 / num2;\n break;\n default:\n break;\n }\n\n operands.push(result);\n } else {\n operands.push(stoi(tokens[i]));\n }\n }\n\n return operands.top();\n }\n};",
"memory": "30931"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<char> st;\n vector<string> rpn;\n string str = \"\";\n char ch;\n bool hasOp = false;\n\n for (int i = 0; i < s.length(); i++) {\n if (s[i] != ' ') {\n str += s[i];\n }\n }\n \n for (int i = 0; i < str.length(); i++) {\n ch = str[i];\n if (ch == ' ') {\n continue;\n }\n \n switch (ch) {\n case '(':\n st.push(ch);\n break;\n case ')':\n st.pop();\n if (!st.empty() && (st.top() == '+' || st.top() == '-')) {\n rpn.push_back(string(1, st.top()));\n st.pop();\n }\n break;\n case '+':\n st.push(ch);\n hasOp = true;\n break;\n case '-':\n if (i == 0 || str[i - 1] == '(') {\n rpn.push_back(\"0\");\n }\n st.push(ch);\n hasOp = true;\n break;\n default:\n if (i > 0 && str[i - 1] >= '0' && str[i - 1] <= '9') {\n rpn.back() += ch;\n } else {\n rpn.push_back(string(1, ch));\n }\n\n if ((i == str.length() - 1 || str[i + 1] < '0' || str[i + 1] > '9') &&\n (!st.empty() && (st.top() == '+' || st.top() == '-'))) {\n rpn.push_back(string(1, st.top()));\n st.pop();\n }\n break;\n }\n\n /*if (ch == '(') {\n st.push(ch);\n } else if (ch == ')') {\n st.pop();\n if (!st.empty() && (st.top() == '+' || st.top() == '-')) {\n //rpn += st.top();\n rpn.push_back(string(1, st.top()));\n st.pop();\n }\n } else if (ch == '+') {\n st.push(ch);\n hasOp = true;\n } else if (ch == '-') {\n if (rpn.empty() || s[i - 1] == '(') {\n rpn.push_back(\"0\");\n }\n st.push(ch);\n hasOp = true;\n } else {\n //rpn += ch;\n rpn.push_back(string(1, ch));\n if (!st.empty() && (st.top() == '+' || st.top() == '-')) {\n //rpn += st.top();\n rpn.push_back(string(1, st.top()));\n st.pop();\n }\n }\n\n prev = ch;*/\n }\n\n if (!hasOp) {\n /*string rpnStr = \"\";\n for (int i = 0; i < rpn.size(); i++) {\n rpnStr += rpn[i];\n }\n return stoi(rpnStr);*/\n //return stoi(rpn);\n }\n return evalRPN(rpn);\n }\n\n int evalRPN(vector<string>& tokens) {\n stack<int> operands;\n int num1 = 0;\n int num2 = 0;\n int result = 0;\n\n for (int i = 0; i < tokens.size(); i++) {\n if (tokens[i] == \"+\" || tokens[i] == \"-\") {\n num2 = operands.top();\n operands.pop();\n num1 = operands.top();\n operands.pop();\n\n switch (tokens[i][0]) {\n case '+':\n result = num1 + num2;\n break;\n case '-':\n result = num1 - num2;\n break;\n case '*':\n result = num1 * num2;\n break;\n case '/':\n result = num1 / num2;\n break;\n default:\n break;\n }\n\n operands.push(result);\n } else {\n operands.push(stoi(tokens[i]));\n }\n }\n\n return operands.top();\n }\n};",
"memory": "31868"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n bool isOperator(string& s)\n {\n return (s == \"+\" || s == \"-\" || s == \"*\" || s == \"/\");\n }\n\n int evalRPN(vector<string>& tokens) {\n stack<int> integerStack{};\n for (auto s : tokens)\n {\n if (!isOperator(s))\n {\n integerStack.push(stoi(s));\n }\n else\n {\n const int operand2 = integerStack.top();\n integerStack.pop();\n const int operand1 = integerStack.top();\n integerStack.pop();\n int result{};\n if (s == \"+\")\n {\n result = operand1 + operand2;\n }\n else if (s == \"-\")\n {\n result = operand1 - operand2;\n }\n else if (s == \"*\")\n {\n result = operand1 * operand2;\n }\n else\n {\n result = operand1 / operand2;\n }\n integerStack.push(result);\n }\n }\n return integerStack.top();\n }\n\n int calculate(string s) {\n vector<string> postfixNotation{};\n stack<char> operatorStack{};\n string integer{};\n bool isLastTokenIntegerOrClosedParenthesis = false;\n for (int i = 0; i < s.size(); ++i)\n {\n while (i < s.size() && isdigit(s[i]))\n {\n integer += s[i++];\n }\n if (integer != \"\")\n {\n isLastTokenIntegerOrClosedParenthesis = true;\n postfixNotation.push_back(integer);\n integer = \"\";\n }\n if (i == s.size())\n {\n break;\n }\n if (s[i] == ' ')\n {\n continue;\n }\n else if (s[i] == '(')\n {\n isLastTokenIntegerOrClosedParenthesis = false;\n operatorStack.push(s[i]);\n }\n else if (s[i] == ')')\n {\n isLastTokenIntegerOrClosedParenthesis = true;\n while (operatorStack.top() != '(')\n {\n postfixNotation.push_back(string{operatorStack.top()});\n operatorStack.pop();\n }\n operatorStack.pop(); // Popping '('\n }\n else if (s[i] == '+')\n {\n isLastTokenIntegerOrClosedParenthesis = false;\n while (!operatorStack.empty() && operatorStack.top() != '(')\n {\n postfixNotation.push_back(string{operatorStack.top()});\n operatorStack.pop();\n }\n operatorStack.push(s[i]);\n }\n else // s[i] == '-'\n {\n if (!isLastTokenIntegerOrClosedParenthesis)\n {\n postfixNotation.push_back(\"0\");\n }\n isLastTokenIntegerOrClosedParenthesis = false;\n while (!operatorStack.empty() && operatorStack.top() != '(')\n {\n postfixNotation.push_back(string{operatorStack.top()});\n operatorStack.pop();\n }\n operatorStack.push(s[i]);\n } \n }\n while (!operatorStack.empty())\n {\n postfixNotation.push_back(string{operatorStack.top()});\n operatorStack.pop();\n }\n\n return evalRPN(postfixNotation);\n }\n};",
"memory": "31868"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "#include <algorithm>\n#include <cctype>\n#include <memory>\n#include <pstl/glue_algorithm_defs.h>\n#include <stack>\n#include <stdexcept>\n#include <string>\n#include <utility>\n\nusing namespace std;\n\nclass Expr {\npublic:\n virtual int eval() const = 0;\n // define descructor since its relied upon by unique_ptr\n virtual ~Expr() = default;\n};\n\nclass Constant : public Expr {\n int value;\n\npublic:\n Constant(int value) : value(value){};\n virtual int eval() const { return value; }\n};\n\nusing ExprPtr = unique_ptr<Expr>;\n\nclass UnaryMinus : public Expr {\n ExprPtr operand;\n\npublic:\n UnaryMinus(ExprPtr operand) : operand(std::move(operand)) {}\n virtual int eval() const { return -operand->eval(); }\n};\n\nclass Binary : public Expr {\n char op;\n ExprPtr left;\n ExprPtr right;\n\npublic:\n Binary(char op, ExprPtr left, ExprPtr right)\n : op(op), left(std::move(left)), right(std::move(right)) {}\n virtual int eval() const {\n switch (op) {\n case '+':\n return left->eval() + right->eval();\n case '-':\n return left->eval() - right->eval();\n }\n throw invalid_argument(\"bad op\");\n }\n};\n\nclass Solution {\npublic:\n int precedence(char op) {\n switch (op) {\n case '+':\n case '-':\n case '_':\n return 1;\n default:\n return 0;\n }\n }\n\n /* Parse the operator op using the given operands */\n void parseOp(char op, stack<ExprPtr> &operands) {\n if (op == '(')\n return;\n if (op == '_') {\n ExprPtr operand = std::move(operands.top());\n operands.pop();\n operands.push(make_unique<UnaryMinus>(std::move(operand)));\n return;\n }\n // binary operator\n ExprPtr right = std::move(operands.top());\n operands.pop();\n ExprPtr left = std::move(operands.top());\n operands.pop();\n operands.push(make_unique<Binary>(op, std::move(left), std::move(right)));\n }\n\n /* Parse the given infix into an expression for evaluation */\n ExprPtr parse(string s) {\n stack<ExprPtr> operands;\n stack<char> ops;\n string operand = \"\";\n\n // remove whitespace from string\n s.erase(remove(s.begin(), s.end(), ' '), s.end());\n\n for (int i = 0; i < s.size(); i++) {\n char c = s[i];\n if (isdigit(c)) {\n operand += c;\n continue;\n }\n // not an operand: parse any existing operand we are building\n if (operand.size() > 0) {\n operands.push(make_unique<Constant>(stoi(operand)));\n operand = \"\";\n }\n // c must be an operator\n if (c == '-' && (i <= 0 || s[i - 1] == '(')) {\n // unary minius: parse as underscore\n ops.push('_');\n continue;\n }\n if (c == '(') {\n ops.push('(');\n continue;\n }\n if (c == ')') {\n // parse until prior '('\n while (ops.top() != '(') {\n parseOp(ops.top(), operands);\n ops.pop();\n }\n // remove '('\n ops.pop();\n continue;\n }\n // evaluate any outstanding operators\n while (ops.size() > 0 && precedence(c) <= precedence(ops.top())) {\n parseOp(ops.top(), operands);\n ops.pop();\n }\n ops.push(c);\n }\n\n // parse any remaining operands & operators\n if (operand.size() > 0) {\n operands.push(make_unique<Constant>(stoi(operand)));\n }\n while (ops.size() > 0) {\n parseOp(ops.top(), operands);\n ops.pop();\n }\n\n return std::move(operands.top());\n }\n\n int calculate(string s) { return parse(s)->eval(); }\n};\n\n",
"memory": "32806"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n vector<string>v;\n // if(s[0]=='+'||s[0]=='-')s=\"0\"+s;\n int i=0;\n while(i<s.size()){\n if(s[i]=='('||s[i]==')'||s[i]=='+'||s[i]=='-'){\n string temp;\n temp.push_back(s[i]);\n // cout<<temp<<endl;\n if(temp==\")\"&&v[v.size()-2]==\"(\")\n {\n v[v.size()-2]=v.back();\n v.pop_back();\n }\n else if(temp==\"-\"){\n if(v.size()==0||v.back()==\"(\")v.push_back(\"0\");\n v.push_back(temp);\n\n }\n else \n v.push_back(temp);\n\n }\n else if(s[i]>='0'&&s[i]<='9'){\n int j=i;\n while(j<s.size()&&s[j]>='0'&&s[j]<='9')j++;\n if(v.size()>1&&v[v.size()-2]==\"(\"){\n string str=v.back();\n v.pop_back();\n if(str==\"+\")v.push_back(s.substr(i,j-i));\n else v.push_back(\"-\"+s.substr(i,j-i));\n }\n else v.push_back(s.substr(i,j-i));\n i=j-1;\n\n\n }\n i++;\n }\n stack<int>operand;\n stack<string>oper;\n // for(auto i:v)cout<<i<<\" \";\n // cout<<\"done\"<<endl;\n \n for(auto i:v){\n // cout<<i<<\" \";\n // if(operand.size())cout<<\"top is \"<<operand.top();\n // if(oper.size())cout<<\"top oper is\"<<oper.top();\n // cout<<endl;\n if((i[0]>='0'&&i[0]<='9')||i.size()>1)operand.push(stoi(i));\n else if(i==\"(\")oper.push(i);\n else if(i==\")\") {\n while(oper.top()!=\"(\"){\n string op=oper.top();\n // if(op==\"(\")continue;\n\n oper.pop();\n // if(oper)\n int a=operand.top();\n operand.pop();\n int b=operand.top();\n operand.pop();\n if(op==\"+\")operand.push(a+b);\n else operand.push(b-a);\n\n\n }\n oper.pop();\n // if(oper.size()&&oper.top()==\"-\"){\n // int t=operand.top();\n // operand.pop();\n // operand.push(-t);\n // oper.pop();\n // oper.push(\"+\");\n\n // }\n\n }\n else if(i==\"+\"||i==\"-\"){\n while(oper.size()&&oper.top()!=\"(\"){\n string op=oper.top();\n // if(op==\"(\")continue;\n oper.pop();\n int a=operand.top();\n operand.pop();\n int b=operand.top();\n operand.pop();\n if(op==\"+\")operand.push(a+b);\n else operand.push(b-a);\n\n\n }\n // if(oper.size()&&oper.top()==\"(\"){\n\n // }\n oper.push(i);\n\n }\n }\n // cout<<\"working\"<<endl;\n // cout<<operand.size()<<oper.size()<<endl;\n while(operand.size()!=1){\n string op=oper.top();\n oper.pop();\n int a=operand.top();\n operand.pop();\n int b=operand.top();\n operand.pop();\n // cout<<a<<\" \"<<op<<\" \"<<b<<endl;\n if(op==\"+\")operand.push(a+b);\n else operand.push(b-a);\n }\n // return -operand.top();\n return operand.top();\n \n }\n};",
"memory": "32806"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "#include <algorithm>\n#include <cassert>\n#include <charconv>\n#include <cstddef>\n#include <iterator>\n#include <optional>\n#include <string>\n#include <string_view>\n#include <vector>\n\nusing namespace std;\nclass Solution {\n public:\n int calculate(string s) {\n auto* const root = buildTree(s);\n return reduceTree(root);\n }\n\n private:\n struct Node {\n char op{' '};\n int number{0};\n Node* left{nullptr};\n Node* right{nullptr};\n };\n struct Op {\n size_t index;\n int nesting_level;\n };\n auto buildTree(std::string_view const s) -> Node* {\n if (s.empty() || std::all_of(s.cbegin(), s.cend(),\n [](char const c) { return c == ' '; })) {\n return nullptr;\n }\n\n auto last_non_nested_plus_index = -1;\n auto last_non_nested_minus_index = -1;\n auto has_any_operators = false;\n auto nesting_level = 0;\n for (size_t i = 0; i < s.size(); ++i) {\n auto const index_from_back = s.size() - i - 1;\n switch (s[index_from_back]) {\n case '(':\n ++nesting_level;\n break;\n case ')':\n --nesting_level;\n break;\n case '-':\n if (last_non_nested_minus_index == -1 && nesting_level == 0) {\n last_non_nested_minus_index = static_cast<int>(index_from_back);\n }\n has_any_operators = true;\n break;\n case '+':\n if (last_non_nested_plus_index == -1 && nesting_level == 0) {\n last_non_nested_plus_index = static_cast<int>(index_from_back);\n }\n has_any_operators = true;\n default:\n break;\n }\n if (last_non_nested_plus_index != -1) {\n break;\n }\n }\n\n if (has_any_operators) {\n if (last_non_nested_minus_index == -1 &&\n last_non_nested_plus_index == -1) {\n auto const trimmed_s = [&]() -> std::string_view {\n auto const trimmed_s_begin = std::find_if(\n s.cbegin(), s.cend(), [](char const c) { return c != ' '; });\n auto const trimmed_s_end = std::find_if(\n s.crbegin(), s.crend(), [](char const c) { return c != ' '; });\n return std::string_view(trimmed_s_begin, trimmed_s_end.base());\n }();\n\n // remove nesting parentheses\n return buildTree(trimmed_s.substr(1, trimmed_s.size() - 2));\n }\n // push minuses down in the tree so they don't multiply too much of the\n // expression by one\n auto const next_operator_index = last_non_nested_plus_index == -1\n ? last_non_nested_minus_index\n : last_non_nested_plus_index;\n auto const next_operator_it = s.cbegin() + next_operator_index;\n auto* new_node = new Node;\n new_node->op = *next_operator_it;\n new_node->left =\n buildTree(std::string_view(s.cbegin(), next_operator_it));\n new_node->right =\n buildTree(std::string_view(next_operator_it + 1, s.cend()));\n\n return new_node;\n }\n // number\n auto const number_begins = std::find_if(\n s.cbegin(), s.cend(),\n [](char const c) { return c != '(' && c != ')' && c != ' '; });\n auto const num_parens_to_trim = std::distance(s.cbegin(), number_begins);\n auto trimmed_s_without_opening_parens = s;\n trimmed_s_without_opening_parens.remove_prefix(\n static_cast<size_t>(num_parens_to_trim));\n auto number = 0;\n std::from_chars(trimmed_s_without_opening_parens.data(),\n trimmed_s_without_opening_parens.data() +\n trimmed_s_without_opening_parens.size(),\n number);\n\n auto* new_node = new Node;\n new_node->number = number;\n return new_node;\n }\n\n auto reduceTree(Node* const root) -> int {\n if (root == nullptr) {\n // lhs of unary -\n return 0;\n }\n if (root->op == ' ') {\n return root->number;\n }\n auto const left_result = reduceTree(root->left);\n auto const right_result = reduceTree(root->right);\n if (root->op == '+') {\n return left_result + right_result;\n }\n if (root->op == '-') {\n return left_result - right_result;\n }\n assert(false);\n return 0;\n }\n};",
"memory": "39368"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n std::string evaluateString(string s)\n {\n std::vector<std::string> equation;\n int res = 0;\n int start = 0;\n\n for (int i = start; i < s.size(); ++i)\n {\n if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')\n {\n if (i == 0)\n {\n if (s[i] == '-' && s[i+1] == '-')\n {\n start = 2;\n ++i;\n }\n continue;\n }\n if (s[i] == '-' && s[i+1] == '-')\n {\n equation.push_back(s.substr(start, i - start));\n equation.push_back(\"+\");\n start = i + 2;\n ++i;\n continue;\n }\n else if (s[i] == '+' && s[i+1] == '-')\n {\n equation.push_back(s.substr(start, i - start));\n equation.push_back(\"-\");\n start = i + 2;\n ++i;\n continue;\n }\n else if (s[i] == '*' && s[i+1] == '-')\n {\n equation.push_back(\"-1\");\n equation.push_back(\"*\");\n equation.push_back(s.substr(start, i - start));\n equation.push_back(\"*\");\n start = i + 2;\n ++i;\n continue;\n }\n else if (s[i] == '*' && s[i+1] == '/')\n {\n equation.push_back(\"-1\");\n equation.push_back(\"*\");\n equation.push_back(s.substr(start, i - start));\n equation.push_back(\"/\");\n start = i + 2;\n ++i;\n continue;\n }\n equation.push_back(s.substr(start, i - start));\n equation.push_back(s.substr(i, 1));\n start = i + 1;\n continue;\n }\n if (i == s.size() - 1)\n {\n equation.push_back(s.substr(start, i - start + 1));\n }\n }\n\n bool multiAndDivDone = false;\n\n while (equation.size() > 1)\n {\n if(!multiAndDivDone)\n {\n for (int i = 0; i < equation.size() - 1; ++i)\n {\n if(equation[i] == \"*\")\n {\n equation[i-1] = std::to_string(std::stoi(equation[i-1]) * std::stoi(equation[i+1]));\n equation.erase(equation.begin() + i, equation.begin() + i + 2);\n break;\n }\n if(equation[i] == \"/\")\n {\n equation[i-1] = std::to_string(std::stoi(equation[i-1]) / std::stoi(equation[i+1]));\n equation.erase(equation.begin() + i, equation.begin() + i + 2);\n break;\n }\n }\n multiAndDivDone = true;\n }\n\n\n for (int i = 0; i < equation.size() - 1; ++i)\n {\n if(equation[i] == \"+\")\n {\n equation[i-1] = std::to_string(std::stoi(equation[i-1]) + std::stoi(equation[i+1]));\n equation.erase(equation.begin() + i, equation.begin() + i + 2);\n break;\n }\n if(equation[i] == \"-\")\n {\n equation[i-1] = std::to_string(std::stoi(equation[i-1]) - std::stoi(equation[i+1]));\n equation.erase(equation.begin() + i, equation.begin() + i + 2);\n break;\n }\n }\n }\n\n return equation[0];//std::stoi(equation[0]);\n }\n\n\n int calculate(string s) {\n s.erase(std::remove_if(s.begin(), s.end(), [](char x){return std::isspace(x);}), s.end());\n int j = 1;\n\n while (true)\n {\n int bracket_start = -1;\n\n for (int i = 0; i < s.length(); ++i)\n {\n if (s[i] == '(') bracket_start = i;\n else if (s[i] == ')')\n {\n std::string result = evaluateString(s.substr(bracket_start + 1, i - bracket_start - 1));\n \n s.replace(bracket_start, i - bracket_start + 1, result);\n\n break;\n }\n }\n if (bracket_start == -1) return std::stoi(evaluateString(s));\n }\n\n return -1;\n }\n};",
"memory": "39368"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n // Convert infix to postfix\n vector<string> postfix;\n stack<string> my_stack;\n string num = \"\";\n bool seen_num = false;\n for (int i = 0; i < s.length(); i++) {\n string c = s.substr(i, 1);\n if ('0' <= c[0] && c[0] <= '9') {\n num += c;\n } else if (num != \"\") {\n postfix.push_back(num);\n num = \"\";\n seen_num = true;\n }\n if (i == s.length() - 1 && num != \"\") {\n postfix.push_back(num);\n }\n if (c == \"(\") {\n my_stack.push(c);\n seen_num = false;\n } else if (c == \")\") {\n while (!my_stack.empty() && my_stack.top() != \"(\") {\n postfix.push_back(my_stack.top());\n my_stack.pop();\n }\n my_stack.pop();\n } else if (c == \"+\" || c == \"-\") { // Operator\n while (!my_stack.empty() && (my_stack.top() == \"+\" || my_stack.top() == \"-\" || my_stack.top() == \"u-\")) {\n postfix.push_back(my_stack.top());\n my_stack.pop();\n }\n if (c == \"-\" && !seen_num) {\n my_stack.push(\"u-\");\n } else {\n my_stack.push(c);\n }\n }\n }\n while (!my_stack.empty()) {\n postfix.push_back(my_stack.top());\n my_stack.pop();\n }\n // Evaluate postfix\n stack<string> eval_stack;\n for (int i = 0; i < postfix.size(); i++) {\n string token = postfix[i];\n if (token == \"u-\") {\n int num = stoi(eval_stack.top());\n eval_stack.pop();\n eval_stack.push(to_string(-num));\n } else if (token == \"+\" || token == \"-\") {\n int second = stoi(eval_stack.top());\n eval_stack.pop();\n int first = stoi(eval_stack.top());\n eval_stack.pop();\n if (token == \"+\") {\n eval_stack.push(to_string(first + second));\n }\n if (token == \"-\") {\n eval_stack.push(to_string(first - second));\n }\n } else {\n eval_stack.push(token);\n }\n }\n return stoi(eval_stack.top());\n }\n};",
"memory": "40306"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n\n enum class NextOperation: uint8_t\n {\n ADD,\n SUBSTRACT\n };\n\n int computeCurrentLine(string s)\n {\n// std::cout << \"Processing \" << std::quoted(s) << std::endl;\n if ((s.front() == '(') and (s.back() == ')'))\n s = s.substr(1, s.length() - 2);\n\n vector<string> operands;\n size_t i = 0;\n while (i < s.length())\n {\n// std::cout << \"Processing at \" << i << std::endl;\n size_t nextToken = s.find_first_of(\"+- \", i);\n if (nextToken != std::string::npos)\n {\n// std::cout << \"Token found at \" << nextToken << std::endl;\n if (nextToken > i)\n {\n operands.push_back(s.substr(i, nextToken - i));\n// std::cout << \"Storing 1 \" << std::quoted(s.substr(i, nextToken - i)) << std::endl; \n }\n operands.push_back(s.substr(nextToken, 1));\n// std::cout << \"Storing 2 \" << std::quoted(s.substr(nextToken, 1)) << std::endl;\n\n i = nextToken + 1;\n }\n else\n {\n operands.push_back(s.substr(i, s.length() - i));\n// std::cout << \"Storing 3 \" << std::quoted(s.substr(i, s.length() - i)) << std::endl;\n break;\n }\n }\n\n // Now, traverse the operands line by line\n int result = 0;\n NextOperation nextOp = NextOperation::ADD;\n for (auto const &operand : operands)\n {\n// std::cout << \"Operand \" << std::quoted(operand) << std::endl;\n if (operand == \"-\")\n {\n if (nextOp == NextOperation::ADD)\n nextOp = NextOperation::SUBSTRACT;\n else\n nextOp = NextOperation::ADD;\n } \n else if (operand == \"+\")\n nextOp = NextOperation::ADD;\n else if (operand == \" \")\n continue;\n else\n {\n switch (nextOp)\n {\n case NextOperation::SUBSTRACT:\n result -= std::stoi(operand);\n break;\n case NextOperation::ADD:\n result += std::stoi(operand);\n break;\n default:\n break; \n }\n nextOp = NextOperation::ADD;\n }\n }\n// std::cout << \"Compute returned \" << result << std::endl;\n return result;\n }\n\n int calculate(string s) {\n // Parse string until a '(' is found.\n // In that case, start a stack until either a ')' is found\n // in which case the stack is parsed, or, if a new '(' is found,\n // a subsequent stack is started and so on\n int result = 0;\n vector<string> parser;\n for (auto const &c: s)\n {\n if (c == '(')\n {\n parser.push_back(std::string(1, c));\n }\n else if (c == ')')\n {\n parser.back().append(1, c);\n // Parse the current line\n result = computeCurrentLine(parser.back());\n // Append the result to the previous line\n parser.pop_back();\n if (parser.empty())\n parser.push_back(std::to_string(result));\n else\n parser.back().append(std::to_string(result));\n }\n else\n {\n if (parser.empty())\n parser.push_back(std::string(1, c));\n else\n parser.back().append(1, c);\n }\n }\n\n if (parser.size() != 1)\n return 0;\n\n return computeCurrentLine(parser.back());\n }\n};",
"memory": "40306"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<string> st;\n vector<string> ans;\n\n //обратная польская запись в стеке\n s += ' ';\n string strV = \"\";\n char prev = ' ';\n for(char ch: s) {\n if(isdigit(ch)) {\n strV += ch;\n prev = ch;\n continue;\n }\n\n if(strV != \"\") {\n ans.push_back(strV);\n strV = \"\";\n }\n\n if(ch == ' ') continue;\n\n if(ch == '(') {\n st.push(\"(\");\n } else if(ch == ')') {\n while(!st.empty() && st.top() != \"(\") {\n ans.push_back(st.top());\n st.pop();\n }\n if(!st.empty() && st.top() == \"(\") st.pop();\n } else if(ch == '+') {\n while(!st.empty() && (st.top() == \"+\" || st.top() == \"-\" )) {\n ans.push_back(st.top());\n st.pop();\n }\n st.push(\"+\");\n } else if(ch == '-') {\n if(!isdigit(prev) && prev != ')') {\n ans.push_back(\"0\");\n } else {\n while(!st.empty() && (st.top() == \"+\" || st.top() == \"-\" )) {\n ans.push_back(st.top());\n st.pop();\n }\n }\n st.push(\"-\");\n } \n\n prev = ch;\n }\n\n while(!st.empty()) {\n string v = st.top();\n st.pop();\n ans.push_back(v);\n }\n \n //вычислить обратную польскую запись\n for(string v: ans) {\n if(v == \"+\") {\n int a = stoi(st.top());\n st.pop();\n int b = stoi(st.top());\n st.pop();\n st.push(to_string(a + b));\n } else if(v == \"-\") {\n int b = stoi(st.top());\n st.pop();\n int a = stoi(st.top());\n st.pop();\n st.push(to_string(a - b));\n } else {\n st.push(v);\n }\n }\n\n return stoi(st.top()); \n }\n};",
"memory": "41243"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n using Num = int64_t;\n using Nil = std::monostate;\n\n enum class UnOp {\n Negate\n };\n\n enum class BiOp {\n Add,\n Sub\n };\n\n using Ops = std::variant<Nil, UnOp, BiOp>;\n\n struct Expr;\n\n using ExprVariant = std::variant<\n Nil,\n Num,\n std::pair<UnOp, std::unique_ptr<Expr>>,\n std::tuple<BiOp, std::unique_ptr<Expr>, std::unique_ptr<Expr>>\n >;\n\n struct Expr {\n ExprVariant val;\n\n Expr() : val(Nil{}) {}\n Expr(Num n) : val(n) {}\n Expr(UnOp unop, std::unique_ptr<Expr> e) : val(std::make_pair(unop, std::move(e))) {}\n Expr(BiOp binop, std::unique_ptr<Expr> e1, std::unique_ptr<Expr> e2) : val(std::make_tuple(binop, std::move(e1), std::move(e2))) {}\n\n // Move constructor\n Expr(Expr&& other) noexcept : val(std::move(other.val)) {}\n\n // Move assignment operator\n Expr& operator=(Expr&& other) noexcept {\n if (this != &other) {\n val = std::move(other.val);\n }\n return *this;\n }\n\n // Delete copy constructor and copy assignment operator\n Expr(const Expr&) = delete;\n Expr& operator=(const Expr&) = delete;\n };\n\n struct Visitor {\n int64_t operator()(Nil) const {\n throw std::runtime_error(\"Can't perform ops with null\");\n }\n\n int64_t operator()(Num n) const {\n return n;\n }\n\n int64_t operator()(const std::pair<UnOp, std::unique_ptr<Expr>>& unop) const {\n auto op = unop.first;\n int64_t v = std::visit(*this, unop.second->val);\n\n switch (op) {\n case UnOp::Negate:\n return -v;\n default:\n throw std::runtime_error(\"Unknown op\");\n }\n }\n\n int64_t operator()(const std::tuple<BiOp, std::unique_ptr<Expr>, std::unique_ptr<Expr>>& biop) const {\n int64_t lhs = std::visit(*this, std::get<1>(biop)->val);\n int64_t rhs = std::visit(*this, std::get<2>(biop)->val);\n auto op = std::get<0>(biop);\n\n switch (op) {\n case BiOp::Add:\n return lhs + rhs;\n case BiOp::Sub:\n return lhs - rhs;\n default:\n throw std::runtime_error(\"Unknown biop\");\n }\n }\n };\n struct ToStringVisitor {\n std::string operator()(Nil) const {\n return \"Nil\";\n }\n\n std::string operator()(Num n) const {\n return std::to_string(n);\n }\n\n std::string operator()(const std::pair<UnOp, std::unique_ptr<Expr>>& unop) const {\n std::string opStr;\n switch (unop.first) {\n case UnOp::Negate:\n opStr = \"-\";\n break;\n default:\n throw std::runtime_error(\"Unknown UnOp\");\n }\n return opStr + \"(\" + std::visit(*this, unop.second->val) + \")\";\n }\n\n std::string operator()(const std::tuple<BiOp, std::unique_ptr<Expr>, std::unique_ptr<Expr>>& biop) const {\n std::string opStr;\n switch (std::get<0>(biop)) {\n case BiOp::Add:\n opStr = \"+\";\n break;\n case BiOp::Sub:\n opStr = \"-\";\n break;\n default:\n throw std::runtime_error(\"Unknown BiOp\");\n }\n return \"(\" + std::visit(*this, std::get<1>(biop)->val) + \" \" + opStr + \" \" + std::visit(*this, std::get<2>(biop)->val) + \")\";\n }\n };\n\n int64_t getNum(string&s, int& i, int end) {\n string num; \n do {\n num += s[i];\n } while (++i < end && std::isdigit(s[i]));\n i--;\n return std::stoll(num);\n }\n\n Expr evaluate(std::string& s, int start, int end) {\n int i = start;\n std::vector<int> stack;\n Ops op = Nil{};\n Expr e;\n\n while (++i < end) {\n if (s[i] == '(') {\n stack.push_back(i);\n int start = stack.back();\n while (!stack.empty()) {\n i++;\n if (s[i] == '(') stack.push_back(i);\n else if (s[i] == ')') {\n start = stack.back(); stack.pop_back();\n }\n }\n if (std::holds_alternative<BiOp>(op)) {\n auto biop = std::get<BiOp>(op);\n switch (biop) {\n case BiOp::Add:\n case BiOp::Sub: {\n e = Expr(biop, std::make_unique<Expr>(std::move(e)), std::make_unique<Expr>(evaluate(s, start, i)));\n break;\n }\n default:\n throw std::runtime_error(\"Unknown biop\");\n }\n } else if (std::holds_alternative<UnOp>(op)) {\n auto unop = std::get<UnOp>(op);\n switch (unop) {\n case UnOp::Negate: {\n e = Expr(unop, std::make_unique<Expr>(evaluate(s, start, i)));\n break;\n }\n default:\n throw std::runtime_error(\"Unknown unop\");\n }\n } else {\n e = evaluate(s, start, i);\n }\n } else if (s[i] == '+') {\n op = BiOp::Add;\n } else if (s[i] == '-') {\n if (std::holds_alternative<Nil>(e.val)) {\n op = UnOp::Negate;\n } else {\n op = BiOp::Sub;\n }\n } else {\n if (std::holds_alternative<BiOp>(op)) {\n auto biop = std::get<BiOp>(op);\n switch (biop) {\n case BiOp::Add:\n case BiOp::Sub: {\n e = Expr(biop, std::make_unique<Expr>(std::move(e)), std::make_unique<Expr>(getNum(s, i, end)));\n break;\n }\n default:\n throw std::runtime_error(\"Unknown biop\");\n }\n } else if (std::holds_alternative<UnOp>(op)) {\n auto unop = std::get<UnOp>(op);\n switch (unop) {\n case UnOp::Negate: {\n e = Expr(unop, std::make_unique<Expr>(getNum(s, i, end)));\n break;\n }\n default:\n throw std::runtime_error(\"Unknown unop\");\n }\n } else {\n e = Expr(getNum(s, i, end));\n // ToStringVisitor toStringVisitor;\n // string expressionStr = std::visit(toStringVisitor, e.val);\n // cout << expressionStr << endl;\n }\n }\n }\n\n return e;\n }\n\n int calculate(string s) {\n s.erase(std::remove(s.begin(), s.end(), ' '), s.end()); \n Expr line = evaluate(s, -1, s.length()); \n // ToStringVisitor toStringVisitor;\n // string expressionStr = std::visit(toStringVisitor, line.val);\n // cout << \"Expression: \" << expressionStr << endl;\n\n Visitor v;\n return std::visit(v, line.val);\n }\n};",
"memory": "41243"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\n\nenum TokenType {\n NUMBER,\n ADD, \n SUBTRACT,\n MULTIPLY,\n DIVIDE,\n OPENING_PARENTHESIS,\n CLOSING_PARENTHESIS\n};\n\nstatic unordered_map<char, TokenType> char_to_type_map;\n\nclass Token {\npublic:\n TokenType type;\n string value;\n Token(TokenType type, const string &value): type(type), value(value) {}\n};\n\n\nclass Lexer {\n int pos;\n string input;\n\npublic:\n Lexer(): pos(0) {}\n\n queue<Token> tokenize(const string &input) {\n //* init\n pos = 0;\n this->input = input;\n\n queue<Token> q;\n while (pos < input.size()) {\n char curr = input[pos];\n if (isspace(curr)) {\n ++pos;\n } else if (isdigit(curr)) {\n q.push(Token(TokenType::NUMBER, readNumber()));\n } else if (char_to_type_map.count(curr)) {\n q.push(Token(char_to_type_map[curr], string(1, curr)));\n ++pos;\n } else {\n throw runtime_error(\"invalid character in input!\");\n }\n }\n return q;\n }\n\nprivate:\n string readNumber() {\n int start = pos;\n while (pos < input.size() && isdigit(input[pos])) ++pos;\n return input.substr(start, pos - start);\n }\n};\n\n\n\n\n\nclass Node {\npublic:\n virtual int evaluate() = 0;\n virtual string to_string() = 0;\n};\n\n\nclass UnaryNegateNode: public Node {\n Node *node;\npublic:\n UnaryNegateNode(Node *node = nullptr): node(node) {}\n \n virtual int evaluate() {\n return - node->evaluate();\n }\n\n virtual string to_string() {\n string res = \"(\";\n res += \"-\";\n res += node->to_string();\n res += \")\";\n return res;\n }\n};\n\nclass AddNode: public Node {\n Node *left, *right;\npublic:\n AddNode(Node *left = nullptr, Node *right = nullptr): left(left), right(right) {}\n\n virtual int evaluate() {\n return left->evaluate() + right->evaluate();\n }\n \n virtual string to_string() {\n string res = \"(\";\n res += left->to_string();\n res += \"+\";\n res += right->to_string();\n res += \")\";\n return res;\n }\n};\n\nclass SubtractNode: public Node {\n Node *left, *right;\npublic:\n SubtractNode(Node *left = nullptr, Node *right = nullptr): left(left), right(right) {}\n\n virtual int evaluate() {\n return left->evaluate() - right->evaluate();\n }\n \n virtual string to_string() {\n string res = \"(\";\n res += left->to_string();\n res += \"-\";\n res += right->to_string();\n res += \")\";\n return res;\n }\n};\n\nclass MultiplyNode: public Node {\n Node *left, *right;\npublic:\n MultiplyNode(Node *left = nullptr, Node *right = nullptr): left(left), right(right) {}\n \n virtual int evaluate() {\n return left->evaluate() * right->evaluate();\n }\n\n \n virtual string to_string() {\n string res = \"(\";\n res += left->to_string();\n res += \"*\";\n res += right->to_string();\n res += \")\";\n return res;\n }\n};\n\nclass DivideNode: public Node {\n Node *left, *right;\npublic:\n DivideNode(Node *left = nullptr, Node *right = nullptr): left(left), right(right) {}\n\n virtual int evaluate() {\n return left->evaluate() / right->evaluate();\n }\n\n \n virtual string to_string() {\n string res = \"(\";\n res += left->to_string();\n res += \"/\";\n res += right->to_string();\n res += \")\";\n return res;\n }\n};\n\nclass NumberNode: public Node {\n string val;\npublic:\n NumberNode(const string &val): val(val) {}\n virtual int evaluate() {\n return stoi(val);\n }\n\n \n virtual string to_string() {\n // cout << \"(\";\n return val;\n // cout << \")\";\n }\n};\n\n\n\n\nclass Parser {\n string input;\n queue<Token> q; \npublic: \n Parser(const string &input): input(input) {\n q = Lexer().tokenize(input); \n }\n\n Node *parse() {\n return parseE();\n }\n\nprivate:\n Token peek() {\n return q.front();\n }\n \n bool match(TokenType type) {\n return (q.size() && q.front().type == type);\n }\n\n Node *parseE() {\n Node *node = parseT();\n // add and subtract operators have equal precedence\n // if both are present left one should be executed first\n while (match(TokenType::ADD) || match(TokenType::SUBTRACT)) {\n TokenType oprtr = peek().type;\n q.pop(); //* consume\n Node *right_node = parseT();\n if (oprtr == TokenType::ADD) node = new AddNode(node, right_node);\n else node = new SubtractNode(node, right_node);\n }\n return node;\n }\n\n Node *parseT() {\n Node *node = parseF();\n // multiply and divide operators have equal precedence\n // if both are present left one should be executed first [that's why this while loop]\n while (match(TokenType::MULTIPLY) || match(TokenType::DIVIDE)) {\n TokenType oprtr = peek().type;\n q.pop(); //* consume\n Node *right_node = parseF();\n if (oprtr == TokenType::MULTIPLY) node = new MultiplyNode(node, right_node);\n else node = new DivideNode(node, right_node);\n }\n return node;\n }\n\n Node *parseF() {\n if (match(TokenType::SUBTRACT)) {\n q.pop();\n return new UnaryNegateNode(parseF());\n } else if (match(TokenType::OPENING_PARENTHESIS)) {\n q.pop();\n Node *node = parseE();\n if (!match(TokenType::CLOSING_PARENTHESIS)) \n throw runtime_error(\"Missing closing parenthesis!\");\n \n q.pop();\n return node;\n } else if (match(TokenType::NUMBER)) {\n Node* node = new NumberNode(peek().value);\n q.pop();\n return node;\n } else {\n throw runtime_error(\"Invalid token!\");\n }\n }\n\n};\npublic:\n int calculate(string s) {\n Parser parser(s);\n return parser.parse()->evaluate();\n }\n};\n\nunordered_map<char, Solution::TokenType> Solution::char_to_type_map = {\n {'+', Solution::ADD},\n {'-', Solution::SUBTRACT},\n {'*', Solution::MULTIPLY},\n {'/', Solution::DIVIDE},\n {'(', Solution::OPENING_PARENTHESIS},\n {')', Solution::CLOSING_PARENTHESIS},\n};",
"memory": "42181"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n typedef variant<int, char> token;\n\n enum class op {\n add,\n sub,\n mul,\n div\n };\n\n op char_to_op(char c) {\n switch(c) {\n case '+':\n return op::add;\n case '-':\n return op::sub;\n case '*':\n return op::mul;\n case '/':\n return op::div;\n default:\n assert(false);\n };\n }\n\n int priority(op t) {\n switch(t) {\n case op::add:\n case op::sub:\n return 0;\n case op::mul:\n case op::div:\n return 1;\n };\n }\n\n bool compare(op a, op b) {\n return priority(a) < priority(b);\n }\n\n struct binop;\n typedef variant<int,binop> ast;\n struct binop {\n op op;\n unique_ptr<ast> left;\n unique_ptr<ast> right;\n };\n\n int eval(ast& ast) {\n if(holds_alternative<int>(ast)) {\n return get<int>(ast);\n } else {\n binop b = get<binop>(std::move(ast));\n int left = eval(*b.left);\n int right = eval(*b.right);\n switch(b.op) {\n case op::add:\n return left + right;\n case op::sub:\n return left - right;\n case op::mul:\n return left * right;\n case op::div:\n return left / right;\n }\n }\n }\n\n void print(ast& ast) {\n if(holds_alternative<int>(ast)) {\n cout << get<int>(ast) << \" \";\n } else {\n binop& b = get<binop>(ast);\n cout << \"(\";\n print(*b.left);\n switch(b.op) {\n case op::add:\n cout << \"+ \";\n break;\n case op::sub:\n cout << \"- \";\n break;\n case op::mul:\n cout << \"* \";\n break;\n case op::div:\n cout << \"/ \";\n break;\n }\n print(*b.right);\n cout << \")\";\n }\n }\n\n optional<ast> after_expr(int& i, const vector<token>& tokens, optional<tuple<op, unique_ptr<ast>>>& on_reserve, ast expr) {\n if(i == tokens.size() || get<char>(tokens[i]) == ')') {\n if(on_reserve.has_value()) {\n auto [ op, left ] = std::move(on_reserve.value());\n return binop(op, std::move(left), make_unique<ast>(std::move(expr)));\n } else {\n return expr;\n }\n } else {\n op new_op = char_to_op(get<char>(tokens[i]));\n if(on_reserve.has_value()) {\n auto [ reserve_op, left ] = std::move(on_reserve.value());\n if(compare(reserve_op, new_op)) {\n i-=2;\n return after_expr(i, tokens, on_reserve, parse(i, tokens));\n } else {\n on_reserve = make_optional(\n make_tuple(new_op,\n make_unique<ast>(\n binop(reserve_op,std::move(left),make_unique<ast>(std::move(expr))))));\n }\n } else {\n on_reserve = make_optional(make_tuple(new_op, make_unique<ast>(std::move(expr))));\n }\n return nullopt;\n }\n }\n\n ast parse(int& i, const vector<token>& tokens) {\n // 1 + 2 + 3 * 2 / 3 + 1\n \n // ((1 + 2) + 3)\n // (((1 + 2) + ((3 * 2) / 3))) + 1) \n\n // eat number, eat op, parse(rest)\n // (1 + (2 + (3 + 4)))\n // loop eat number, eat op, eat number\n // ((1 + 2) + ((3 * 2) / 3) + 1)\n\n // check if next thing is number+binop, if it's a higher precedence binop than previous, recurse on number+binop\n\n // unary minus for first thing \n // maybe parse unary minus as 0 - ...\n\n optional<tuple<op, unique_ptr<ast>>> on_reserve;\n if(holds_alternative<char>(tokens[i])) {\n char c = get<char>(tokens[i]);\n if(c == '-') {\n on_reserve = make_optional(make_tuple(op::sub, make_unique<ast>(0)));\n ++i;\n } else if(c == '(') {}\n else {\n assert(false);\n }\n } \n for(; i < tokens.size(); ++i) {\n ast v;\n if(holds_alternative<char>(tokens[i])) {\n char c = get<char>(tokens[i]);\n assert(c == '(');\n ++i;\n v = parse(i, tokens);\n } else {\n v = get<int>(tokens[i]);\n }\n ++i;\n optional<ast> ret = after_expr(i, tokens, on_reserve, std::move(v));\n if(ret.has_value()) {\n return std::move(ret.value());\n }\n }\n assert(false);\n }\n\n int calculate(string s) {\n vector<token> tokens;\n for(int i = 0; i < s.size();) {\n if(s[i] == ' ') { ++i; continue; }\n if(isdigit(s[i])) {\n int start = i;\n while(i < s.size() && isdigit(s[i])) {\n ++i;\n }\n int len = i-start;\n int val = stoi(s.substr(start,len));\n tokens.push_back(val);\n } else {\n tokens.push_back(s[i]);\n ++i;\n }\n }\n int i = 0;\n ast tree = parse(i, tokens);\n //print(tree);\n return eval(tree);\n }\n};",
"memory": "42181"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n bool isDigit(char c) {\n return '0' <= c && c <= '9';\n }\n int calculate(string s) {\n s = \"(\" + s + \")\"; // trigger top-level evaluation\n vector<string> tokenize;\n for (int i = 0; i < s.size(); /* manual update */) {\n char c = s[i];\n if (isDigit(c)) {\n string num = \"\";\n for (; i < s.size(); i++) {\n char c = s[i];\n if (isDigit(c)) {\n num += c;\n } else {\n break;\n }\n }\n tokenize.push_back(num);\n } else if (c == '+') {\n tokenize.push_back(\"+\");\n i++;\n } else if (c == '-') {\n tokenize.push_back(\"-\");\n i++;\n } else if (c == '(') {\n tokenize.push_back(\"(\");\n i++;\n } else if (c == ')') {\n tokenize.push_back(\")\");\n i++;\n } else {\n i++;\n }\n }\n reverse(tokenize.begin(), tokenize.end());\n deque<string> steak;\n for (int i = 0; i < tokenize.size(); i++) {\n const string& cur = tokenize[i];\n if (cur == \")\") {\n steak.push_back(cur);\n } else if (cur == \"(\") {\n int value = 0;\n char prior_op = '+';\n while (true) {\n string top = steak.back();\n steak.pop_back();\n if (top == \")\") {\n steak.push_back(to_string(value));\n break;\n } else if (top == \"-\") {\n prior_op = '-';\n } else if (top == \"+\") {\n prior_op = '+';\n } else {\n if (prior_op == '+') {\n value += stoi(top);\n } else {\n value -= stoi(top);\n }\n }\n }\n } else if (cur == \"+\") {\n steak.push_back(cur);\n } else if (cur == \"-\") {\n steak.push_back(cur);\n } else {\n steak.push_back(cur);\n }\n }\n return stoi(steak[0]);\n }\n};",
"memory": "43118"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n vector<string> v;\n v.push_back(\"(\");\n string t = \"\";\n for(int i = 0; i<s.length(); i++) if(s[i] != ' ') t += s[i];\n s = t;\n for(int i = 0;i < s.length(); i++){\n if(s[i] >= '0' && s[i] <= '9'){\n string temp = \"\";\n while(s[i] >= '0' && s[i] <= '9'){\n temp += s[i];\n i++;\n }\n i--;\n v.push_back(temp);\n }\n else if(s[i] != ' '){\n string temp = \"\";\n temp += s[i];\n v.push_back(temp);\n }\n } \n v.push_back(\")\");\n stack<string> st;\n for(int i = 0; i < v.size(); i++){\n if(v[i] != \")\"){\n st.push(v[i]);\n }\n else{\n int temp = 0;\n while(st.top() != \"(\"){\n int k = stoi(st.top());\n st.pop();\n if(st.top() == \"+\"){\n temp += k;\n st.pop();\n }\n else if(st.top() == \"-\"){\n temp -=k;\n st.pop();\n }\n else temp += k;\n }\n st.pop();\n st.push(to_string(temp));\n }\n }\n return stoi(st.top());\n }\n};",
"memory": "43118"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n string str = \"\";\n int n = s.size();\n\n bool isAny = false;\n for(int i = 0; i < n; i++){\n if(s[i] != ' '){\n str += s[i];\n }\n if(s[i] == '+' || s[i] == '-' || s[i] == '(' || s[i] == ')'){\n isAny = true;\n }\n }\n if(isAny == false){\n // reverse(str.begin(), str.end());\n cout << \"sd\" << endl;\n long long v = stol(str);\n return stol(str);\n }\n n = str.size();\n cout << str << \" \" << n << endl;\n string mp[300001];\n string arr[300001];\n\n int fpointer = 0;\n\n for(int i = 0; i < n; i++){\n //cout << fpointer << endl;\n if(str[i] == '+'){\n fpointer++;\n arr[fpointer] = \"+\";\n }\n else if(str[i] == '-'){\n fpointer++;\n arr[fpointer] = \"-\";\n }\n else if(str[i] == '('){\n fpointer++;\n arr[fpointer] = \"(\";\n\n }\n else if(str[i] == ')'){\n stack<string>st;\n // cout << \"here\" << endl;\n while(1){\n if(arr[fpointer] == \"(\"){\n fpointer--;\n break;\n }\n // cout << arr[fpointer] << \" \";\n st.push(arr[fpointer]);\n fpointer--;\n }\n int cal = 0;\n if(st.top() == \"-\"){\n cal = -1;\n st.pop();\n string v = st.top();\n cal = -1 * stoi(v);\n st.pop();\n }\n else{\n string v = st.top();\n st.pop();\n cal = stoi(v);\n }\n string sign = \"+\";\n while(!st.empty()){\n string currentV = st.top();\n st.pop();\n if(currentV == \"+\"){\n sign = \"+\";\n }\n else if(currentV == \"-\"){\n sign = \"-\";\n }\n else{\n if(sign == \"+\"){\n cal += stoi(currentV);\n }\n else{\n cal -= stoi(currentV);\n }\n }\n }\n fpointer++;\n arr[fpointer] = to_string(cal);\n }\n else{\n int num = 0;\n while(1){\n if(i == n){\n break;\n }\n if(str[i] == '+' || str[i] == '-' || str[i] == '(' || str[i] == ')'){\n i--;\n break;\n }\n int digit = str[i]-'0';\n num = num * 10 + digit;\n i++;\n }\n fpointer++;\n arr[fpointer] = to_string(num);\n \n }\n }\n\n stack<string>st;\n\n for(int i = fpointer; i >= 1; i--){\n st.push(arr[i]);\n }\n\n long long cal = 0;\n if(st.top() == \"-\"){\n cal = -1;\n st.pop();\n string v = st.top();\n cal = -1 * stoi(v);\n st.pop();\n }\n else{\n string v = st.top();\n st.pop();\n cal = stoi(v);\n }\n string sign = \"+\";\n while(!st.empty()){\n string currentV = st.top();\n st.pop();\n if(currentV == \"+\"){\n sign = \"+\";\n }\n else if(currentV == \"-\"){\n sign = \"-\";\n }\n else{\n if(sign == \"+\"){\n cal += stoll(currentV);\n }\n else{\n cal -= stoi(currentV);\n }\n }\n }\n\n return cal;\n }\n};",
"memory": "44056"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n struct ASTNode {\n ASTNode(char op_, const std::shared_ptr<ASTNode> &arg1_, const std::shared_ptr<ASTNode> &arg2_)\n : op {op_}, value {0}, arg1 {arg1_}, arg2 {arg2_}\n {}\n ASTNode(char op_, const std::shared_ptr<ASTNode> &arg1_)\n : op {op_}, value {0}, arg1 {arg1_}\n {}\n ASTNode(char op_, int value_ = 0)\n : op {op_}, value {value_}\n {}\n\n char op;\n int value = 0;\n std::shared_ptr<ASTNode> arg1 = nullptr;\n std::shared_ptr<ASTNode> arg2 = nullptr;\n };\n\n static inline int eval(const std::shared_ptr<ASTNode> &node) {\n switch(node->op) {\n case '=': return node->value;\n case '+': return eval(node->arg1) + eval(node->arg2);\n case '-': return eval(node->arg1) - eval(node->arg2);\n default: return 0;\n }\n }\n\n static inline std::shared_ptr<ASTNode> parse_ast(const std::string &s, int &pos);\n static inline std::shared_ptr<ASTNode> parse_term(const std::string &s, int &pos);\n static inline std::shared_ptr<ASTNode> parse_digit(const std::string &s, int &pos);\n\n static inline void skip_spaces(const std::string &s, int &pos) {\n while(pos < s.size() && s[pos] == ' ') {\n ++pos;\n }\n }\n\n int calculate(string s) {\n int pos = 0;\n auto node = parse_ast(s, pos);\n return eval(node);\n }\n};\n\n inline std::shared_ptr<Solution::ASTNode> Solution::parse_term(const std::string &s, int &pos) {\n skip_spaces(s, pos);\n if(s[pos] == '(') {\n ++pos;\n auto node = parse_ast(s, pos);\n skip_spaces(s, pos);\n if(s[pos++] != ')') {\n //TODO: handle this\n }\n return node;\n }\n return parse_digit(s, pos);\n }\n\n inline std::shared_ptr<Solution::ASTNode> Solution::parse_ast(const std::string &s, int &pos) {\n std::shared_ptr<ASTNode> node = nullptr;\n skip_spaces(s, pos);\n if(s[pos] == '-') {\n ++pos;\n node = std::make_shared<ASTNode>(\n '-',\n std::make_shared<ASTNode>('='),\n parse_term(s, pos)\n );\n } else {\n node = parse_term(s, pos);\n }\n\n skip_spaces(s, pos);\n while(pos < s.size() && (s[pos] == '+' || s[pos] == '-')) {\n auto new_node = std::make_shared<ASTNode>(\n s[pos++],\n node\n );\n\n new_node->arg2 = parse_term(s, pos);\n node = new_node;\n }\n\n return node;\n }\n\n inline std::shared_ptr<Solution::ASTNode> Solution::parse_digit(const std::string &s, int &pos) {\n skip_spaces(s, pos);\n\n std::ostringstream stream;\n while(pos < s.size() && (s[pos] >= '0' && s[pos] <= '9')) {\n stream << s[pos++];\n }\n\n skip_spaces(s, pos);\n auto val = std::stoi(stream.str());\n return std::make_shared<ASTNode>('=', val);\n }\n",
"memory": "44993"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "struct Operand \n{\n string s; \n bool isDigit = false; \n bool isLeftPar = false;\n bool isRightPar = false;\n bool isMinus = false;\n bool isPlus = false;\n int val = INT_MIN;\n int sign = 1;\n Operand(const string& _s): s(_s)\n {\n if (s.length() >= 2)\n {\n isDigit = true; \n val = atoi(s.data());\n }\n else if (('0' <= s[0]) && (s[0] <= '9'))\n {\n isDigit = true; \n val = s[0] - '0';\n }\n if (s[0] == '(')\n {\n isLeftPar = true;\n }\n if (s[0] == ')')\n {\n isRightPar = true;\n }\n if (s[0] == '+')\n {\n isPlus = true;\n }\n if (s[0] == '-')\n {\n isMinus = true;\n }\n }\n};\nclass Solution {\n\npublic:\n int process(string s)\n {\n vector<Operand*> sWords; \n stack<Operand*> sOperands;\n sWords.push_back(new Operand(\"(\"));\n for (int idx = 0; idx < s.length(); idx++)\n {\n if (s[idx] == ' ')\n {\n continue;\n }\n sWords.push_back(new Operand(string(1, s[idx])));\n }\n sWords.push_back(new Operand(\")\"));\n\n int curSign = 1;\n for (int idx = 0; idx < sWords.size(); idx++)\n {\n auto& operand = sWords[idx];\n Operand* nextOperand = nullptr;\n Operand* prevOperand = nullptr;\n if ((idx + 1) < sWords.size())\n {\n nextOperand = sWords[idx + 1];\n }\n if (idx - 1 >= 0)\n {\n prevOperand = sWords[idx - 1];\n }\n if (operand->isLeftPar)\n {\n operand->sign = curSign;\n sOperands.push(operand);\n curSign = 1;\n }\n else if (operand->isPlus)\n {\n curSign = 1;\n sOperands.push(operand);\n // cout << \"PUSHED +\" << endl;\n }\n else if (operand->isMinus)\n {\n curSign = -1;\n if ((prevOperand != nullptr) && ((prevOperand->isDigit || prevOperand->isRightPar)))\n {\n operand->isMinus = false;\n operand->isPlus = true;\n // Pushing the sign to the left parenthesis or the digit. \n sOperands.push(operand);\n }\n } \n else if (operand->isDigit)\n {\n if ((prevOperand != nullptr) && (prevOperand->isDigit))\n {\n sOperands.top()->val = sOperands.top()->val * 10 + curSign * operand->val; \n }\n else \n {\n operand->val = curSign * operand->val;\n // cout << \"D\" << operand->val << endl;\n sOperands.push(operand);\n }\n }\n else if (operand->isRightPar)\n {\n int parSign = 1;\n while (true)\n {\n // Number \n if (sOperands.top()->isLeftPar)\n {\n // cout << \"ONE LEFT\" << endl;\n sOperands.pop();\n break;\n }\n Operand* op1 = sOperands.top();\n sOperands.pop();\n cout << op1->val << endl;\n if (sOperands.top()->isLeftPar)\n {\n // cout << \"ONE LEFT ONE DIGIT\" << endl;\n parSign = sOperands.top()->sign;\n sOperands.pop();\n // cout << \"PAR REMOVE\" << op1->val << endl;\n sOperands.push(op1);\n break;\n }\n // Potential operator -> should be always +\n // cout << \"HERE\" << endl;\n Operand* oper = sOperands.top();\n sOperands.pop();\n if (!oper->isPlus)\n {\n // cout << oper->s << \"PROBLEM\" << endl;\n }\n if (sOperands.top()->isLeftPar)\n {\n parSign = sOperands.top()->sign;\n sOperands.pop();\n sOperands.push(op1);\n break;\n }\n // Potential another number \n Operand* op2 = sOperands.top();\n sOperands.pop();\n // cout << \"HERE 3\" << endl;\n if (sOperands.top()->isLeftPar)\n {\n parSign = sOperands.top()->sign;\n }\n // cout << \"V1: \" << op1->val << \" \" << op2->val << endl;\n int sum = op1->val + op2->val;\n sOperands.push(new Operand(to_string(sum)));\n // cout << \"SUM PUSHED\" << sOperands.top()->val << endl;\n }\n sOperands.top()->val = parSign * sOperands.top()->val;\n // cout << \"TOP AFTER REMOVAL \" << sOperands.top()->val << endl;;\n }\n }\n int val = sOperands.top()->val;\n return val;\n }\n\n int calculate(string s) {\n int val = process(s);\n return val;\n }\n};",
"memory": "45931"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "struct Operand \n{\n string s; \n bool isDigit = false; \n bool isLeftPar = false;\n bool isRightPar = false;\n bool isMinus = false;\n bool isPlus = false;\n int val = INT_MIN;\n int sign = 1;\n Operand(const string& _s): s(_s)\n {\n if (s.length() >= 2)\n {\n isDigit = true; \n val = atoi(s.data());\n }\n else if (('0' <= s[0]) && (s[0] <= '9'))\n {\n isDigit = true; \n val = s[0] - '0';\n }\n if (s[0] == '(')\n {\n isLeftPar = true;\n }\n if (s[0] == ')')\n {\n isRightPar = true;\n }\n if (s[0] == '+')\n {\n isPlus = true;\n }\n if (s[0] == '-')\n {\n isMinus = true;\n }\n }\n};\nclass Solution {\n\npublic:\n int process(string s)\n {\n vector<Operand*> sWords; \n stack<Operand*> sOperands;\n sWords.push_back(new Operand(\"(\"));\n for (int idx = 0; idx < s.length(); idx++)\n {\n if (s[idx] == ' ')\n {\n continue;\n }\n sWords.push_back(new Operand(string(1, s[idx])));\n }\n sWords.push_back(new Operand(\")\"));\n\n int curSign = 1;\n for (int idx = 0; idx < sWords.size(); idx++)\n {\n auto& operand = sWords[idx];\n Operand* nextOperand = nullptr;\n Operand* prevOperand = nullptr;\n if ((idx + 1) < sWords.size())\n {\n nextOperand = sWords[idx + 1];\n }\n if (idx - 1 >= 0)\n {\n prevOperand = sWords[idx - 1];\n }\n if (operand->isLeftPar)\n {\n operand->sign = curSign;\n sOperands.push(operand);\n curSign = 1;\n }\n else if (operand->isPlus)\n {\n curSign = 1;\n sOperands.push(operand);\n // cout << \"PUSHED +\" << endl;\n }\n else if (operand->isMinus)\n {\n curSign = -1;\n if ((prevOperand != nullptr) && ((prevOperand->isDigit || prevOperand->isRightPar)))\n {\n operand->isMinus = false;\n operand->isPlus = true;\n // Pushing the sign to the left parenthesis or the digit. \n sOperands.push(operand);\n }\n } \n else if (operand->isDigit)\n {\n if ((prevOperand != nullptr) && (prevOperand->isDigit))\n {\n sOperands.top()->val = sOperands.top()->val * 10 + curSign * operand->val; \n }\n else \n {\n operand->val = curSign * operand->val;\n // cout << \"D\" << operand->val << endl;\n sOperands.push(operand);\n }\n }\n else if (operand->isRightPar)\n {\n int parSign = 1;\n while (true)\n {\n // Number \n if (sOperands.top()->isLeftPar)\n {\n // cout << \"ONE LEFT\" << endl;\n sOperands.pop();\n break;\n }\n Operand* op1 = sOperands.top();\n sOperands.pop();\n cout << op1->val << endl;\n if (sOperands.top()->isLeftPar)\n {\n // cout << \"ONE LEFT ONE DIGIT\" << endl;\n parSign = sOperands.top()->sign;\n sOperands.pop();\n // cout << \"PAR REMOVE\" << op1->val << endl;\n sOperands.push(op1);\n break;\n }\n // Potential operator -> should be always +\n // cout << \"HERE\" << endl;\n Operand* oper = sOperands.top();\n sOperands.pop();\n if (!oper->isPlus)\n {\n // cout << oper->s << \"PROBLEM\" << endl;\n }\n if (sOperands.top()->isLeftPar)\n {\n parSign = sOperands.top()->sign;\n sOperands.pop();\n sOperands.push(op1);\n break;\n }\n // Potential another number \n Operand* op2 = sOperands.top();\n sOperands.pop();\n // cout << \"HERE 3\" << endl;\n if (sOperands.top()->isLeftPar)\n {\n parSign = sOperands.top()->sign;\n }\n // cout << \"V1: \" << op1->val << \" \" << op2->val << endl;\n int sum = op1->val + op2->val;\n sOperands.push(new Operand(to_string(sum)));\n // cout << \"SUM PUSHED\" << sOperands.top()->val << endl;\n }\n sOperands.top()->val = parSign * sOperands.top()->val;\n // cout << \"TOP AFTER REMOVAL \" << sOperands.top()->val << endl;;\n }\n }\n int val = sOperands.top()->val;\n return val;\n }\n\n int calculate(string s) {\n int val = process(s);\n return val;\n }\n};",
"memory": "46868"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n vector<string> arr;\n for (int i = 0; i < s.size(); i++) {\n if (s[i] == ' ') {\n continue;\n }\n else if (s[i] == '(' || s[i] == '+' || s[i] == '-') {\n string t = \"\";\n arr.push_back(t + s[i]);\n } else if (s[i] == ')') {\n vector<string> temp;\n while (arr.back() != \"(\") {\n temp.push_back(arr.back());\n arr.pop_back();\n }\n arr.pop_back();\n std::reverse(temp.begin(), temp.end());\n arr.push_back(helper(temp));\n } else {\n if (arr.empty() || arr.back()[0] == '+' ||\n arr.back()[0] == '-' || arr.back()[0] == '(') {\n string t = \"\";\n arr.push_back(t + s[i]);\n } else {\n arr.back() += s[i];\n }\n }\n // for (auto a : arr) {\n // cout << a;\n // }\n // cout << \"\\n\";\n }\n return stoi(helper(arr));\n }\n\n string helper(vector<string>& input) {\n if (input.size() == 1) {\n return input[0];\n }\n\n if (input[0] == \"-\") {\n input.insert(input.begin(), \"0\");\n }\n\n vector<string> stack;\n int i = 0;\n while (i < input.size()) {\n if (input[i] == \"+\") {\n int res = stoi(stack.back()) + stoi(input[i + 1]);\n stack.pop_back();\n stack.push_back(to_string(res));\n i += 2;\n } else if (input[i] == \"-\") {\n int res = stoi(stack.back()) - stoi(input[i + 1]);\n stack.pop_back();\n stack.push_back(to_string(res));\n i += 2;\n } else {\n stack.push_back(input[i]);\n i += 1;\n }\n }\n return stack[0];\n }\n};",
"memory": "46868"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n string ss;\n for (char c : s) {\n if (c != ' ') {\n ss += c;\n }\n }\n\n if (ss[0] == '-') {\n ss = '0' + ss;\n }\n\n vector<string> arr;\n for (int i = 0; i < ss.size(); i++) {\n if (ss[i] == '(' || ss[i] == '+' || ss[i] == '-') {\n string t = \"\";\n arr.push_back(t + ss[i]);\n } else if (ss[i] == ')') {\n vector<string> temp;\n while (arr.back() != \"(\") {\n temp.push_back(arr.back());\n arr.pop_back();\n }\n arr.pop_back();\n std::reverse(temp.begin(), temp.end());\n arr.push_back(helper(temp));\n } else {\n if (arr.empty() || arr.back()[0] == '+' ||\n arr.back()[0] == '-' || arr.back()[0] == '(') {\n string t = \"\";\n arr.push_back(t + ss[i]);\n } else {\n arr.back() += ss[i];\n }\n }\n // for (auto a : arr) {\n // cout << a;\n // }\n // cout << \"\\n\";\n }\n return stoi(helper(arr));\n }\n\n string helper(vector<string>& input) {\n if (input.size() == 1) {\n return input[0];\n }\n\n if (input[0] == \"-\") {\n input.insert(input.begin(), \"0\");\n }\n\n vector<string> stack;\n int i = 0;\n while (i < input.size()) {\n if (input[i] == \"+\") {\n int res = stoi(stack.back()) + stoi(input[i + 1]);\n stack.pop_back();\n stack.push_back(to_string(res));\n i += 2;\n } else if (input[i] == \"-\") {\n int res = stoi(stack.back()) - stoi(input[i + 1]);\n stack.pop_back();\n stack.push_back(to_string(res));\n i += 2;\n } else {\n stack.push_back(input[i]);\n i += 1;\n }\n }\n return stack[0];\n }\n};",
"memory": "47806"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\nint make_oper(string oper, int first, int second)\n{\n if (oper == \"+\") return first + second;\n else return first - second;\n}\nint calculate(string s)\n{\n stack<string> calc;\n\n int i = 0, res = 0;\n string d;\n while (i < s.size())\n {\n if (s[i] == ' ')\n {\n i++;\n continue;\n }\n\n if (s[i] == ')')\n {\n vector<string> now;\n if (d.size()) calc.push(d);\n d.clear();\n while (calc.top() != \"(\")\n {\n now.push_back(calc.top());\n calc.pop();\n }\n calc.pop();\n reverse(now.begin(), now.end());\n int cur = 0;\n string f = \"-\";\n for (int j = 0; j < now.size(); ++j)\n {\n if (now[j] == \"-\" || now[j] == \"+\")\n {\n if (j == 0)\n {\n j++;\n cur -= (stoi(now[j]));\n }\n else\n {\n j++;\n if (f == \"-\")\n {\n cur = make_oper(now[j - 1], cur, stoi(now[j]));\n }\n else\n {\n \n cur += make_oper(now[j - 1], stoi(f), stoi(now[j]));\n }\n f = \"-\";\n }\n }\n else\n {\n f = now[j];\n }\n }\n if (f != \"-\") cur = stoi(f);\n i++;\n calc.push(to_string(cur));\n }\n else if (isdigit(s[i]))\n {\n d += s[i];\n i++;\n }\n else\n {\n if(d.size())\n calc.push(d);\n string t;\n t += s[i];\n calc.push(t);\n i++;\n d.clear();\n }\n\n }\n if (d.size()) calc.push(d);\n if (calc.size() > 1)\n {\n vector<string> t;\n while (calc.size())\n {\n t.push_back(calc.top());\n calc.pop();\n }\n reverse(t.begin(), t.end());\n string f = \"-\";\n for (int i = 0; i < t.size(); ++i)\n {\n if (t[i] == \"-\" || t[i] == \"+\")\n {\n if (i == 0)\n {\n i++;\n res -= stoi(t[i]);\n }\n\n else if (f == \"-\")\n {\n res = make_oper(t[i], res, stoi(t[i + 1]));\n i++;\n }\n else\n {\n res += make_oper(t[i], stoi(f), stoi(t[i + 1]));\n i++;\n }\n f = \"-\";\n }\n else\n {\n f = t[i];\n }\n }\n }\n else\n {\n res = stoi(calc.top());\n }\n return res;\n}\n};",
"memory": "47806"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\nint make_oper(string oper, int first, int second)\n{\n if (oper == \"+\") return first + second;\n else return first - second;\n}\nint calculate(string s)\n{\n stack<string> calc;\n\n int i = 0, res = 0;\n string d;\n while (i < s.size())\n {\n if (s[i] == ' ')\n {\n i++;\n continue;\n }\n\n if (s[i] == ')')\n {\n vector<string> now;\n if (d.size()) calc.push(d);\n d.clear();\n while (calc.top() != \"(\")\n {\n now.push_back(calc.top());\n calc.pop();\n }\n calc.pop();\n reverse(now.begin(), now.end());\n int cur = 0;\n string f = \"-\";\n for (int j = 0; j < now.size(); ++j)\n {\n if (now[j] == \"-\" || now[j] == \"+\")\n {\n if (j == 0)\n {\n j++;\n cur -= (stoi(now[j]));\n }\n else\n {\n j++;\n if (f == \"-\")\n {\n cur = make_oper(now[j - 1], cur, stoi(now[j]));\n }\n else\n {\n \n cur += make_oper(now[j - 1], stoi(f), stoi(now[j]));\n }\n f = \"-\";\n }\n }\n else\n {\n f = now[j];\n }\n }\n if (f != \"-\") cur = stoi(f);\n i++;\n calc.push(to_string(cur));\n }\n else if (isdigit(s[i]))\n {\n d += s[i];\n i++;\n }\n else\n {\n if(d.size())\n calc.push(d);\n string t;\n t += s[i];\n calc.push(t);\n i++;\n d.clear();\n }\n\n }\n if (d.size()) calc.push(d);\n if (calc.size() > 1)\n {\n vector<string> t;\n while (calc.size())\n {\n t.push_back(calc.top());\n calc.pop();\n }\n reverse(t.begin(), t.end());\n string f = \"-\";\n for (int i = 0; i < t.size(); ++i)\n {\n if (t[i] == \"-\" || t[i] == \"+\")\n {\n if (i == 0)\n {\n i++;\n res -= stoi(t[i]);\n }\n\n else if (f == \"-\")\n {\n res = make_oper(t[i], res, stoi(t[i + 1]));\n i++;\n }\n else\n {\n res += make_oper(t[i], stoi(f), stoi(t[i + 1]));\n i++;\n }\n f = \"-\";\n }\n else\n {\n f = t[i];\n }\n }\n }\n else\n {\n res = stoi(calc.top());\n }\n return res;\n}\n};",
"memory": "48743"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<string> st;\n s += \")\";\n st.push(\"(\");\n for(int i = 0; i<s.size(); i++){\n if(s[i]==' '){continue;}\n else if(s[i] == '('){st.push(\"(\");}\n else if(s[i] == '-'){st.push(\"-\");}\n else if(s[i] == '+'){st.push(\"+\");}\n else if(s[i] == ')'){\n vector<string> temp;\n while(st.top() != \"(\"){\n temp.push_back(st.top());\n st.pop();\n }\n st.pop();\n reverse(temp.begin(),temp.end());\n // for(auto x:temp){cout<<x<<endl;}\n int sum = 0;\n int j = 0;\n if(temp[0]!=\"-\"){\n sum = stoi(temp[0]);\n j++;\n }\n while(j<temp.size()){\n if(temp[j] == \"-\"){\n int num = stoi(temp[j] + temp[j+1]);\n j+=2;\n sum += num;\n }\n else if(temp[j] == \"+\"){\n int num = stoi(temp[j+1]);\n j+=2;\n sum += num;\n }\n else{j+=2;}\n }\n if(st.empty()){\n if(sum<0){\n st.push(\"-\");\n sum = -sum;\n }\n st.push(to_string(sum));\n }\n else if(st.top() == \"(\"){\n if(sum<0){\n st.push(\"-\");\n sum = -sum;\n }\n st.push(to_string(sum));\n }\n else if(st.top() == \"+\"){\n if(sum<0){\n st.pop();\n st.push(\"-\");\n sum = -sum;\n st.push(to_string(sum));\n }\n else{\n st.push(to_string(sum));\n }\n }\n else if(st.top() == \"-\"){\n // cout<<\"here\"<<endl;\n if(sum<0){\n st.pop();\n if(st.size()>=2){st.push(\"+\");}\n sum = -sum;\n st.push(to_string(sum));\n }\n else{\n st.push(to_string(sum));\n }\n }\n\n }\n else{\n int fullnum = 0;\n while(i<s.size()){\n int num = s[i]-'0';\n if(num>=0 && num<=9){fullnum = 10*fullnum + num;}\n else{\n i--;\n break;\n }\n i++;\n }\n st.push(to_string(fullnum));\n }\n }\n // cout<<st.size()<<endl;\n if(st.size()==1){return stoi(st.top());}\n else{\n // while(!st.empty()){cout<<st.top()<<endl;\n // st.pop();}\n return -1*stoi(st.top());\n return -1;\n }\n }\n};",
"memory": "49681"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n map<string, int> OPS = {\n {\"+\", 1},\n {\"-\", 1},\n {\"UNARY_NEGATE\", 2},\n {\"(\", 3},\n {\")\", 3},\n };\n\n vector<string> getTokens(string& s) {\n int idx = 0;\n vector<string> tokens;\n while (idx < s.size()) {\n while (idx < s.size() && isspace(s[idx])) idx++;\n if (idx < s.size()) {\n string token = \"\";\n if (isdigit(s[idx])) {\n while (idx < s.size() && isdigit(s[idx])) {\n token += s[idx++];\n }\n } else {\n token += s[idx++];\n }\n if (token == \"-\" && (tokens.empty() || tokens.back() == \"(\")) {\n token = \"UNARY_NEGATE\";\n } \n tokens.push_back(token);\n }\n }\n return tokens;\n }\n\n vector<string> convertToRPN(string& s) {\n vector<string> rpn;\n stack<string> opsStack;\n\n for (auto& token : getTokens(s)) {\n if (OPS.find(token) != end(OPS)) {\n if (token == \"(\") {\n opsStack.push(token);\n } else if (token == \")\") {\n while (opsStack.top() != \"(\") {\n rpn.push_back(opsStack.top());\n opsStack.pop();\n }\n opsStack.pop();\n } else if (opsStack.empty() || OPS[opsStack.top()] < OPS[token]) {\n opsStack.push(token);\n } else {\n while (!opsStack.empty() && opsStack.top() != \"(\") {\n rpn.push_back(opsStack.top());\n opsStack.pop();\n }\n opsStack.push(token);\n }\n } else {\n rpn.push_back(token);\n }\n }\n\n while (!opsStack.empty()) { \n rpn.push_back(opsStack.top());\n opsStack.pop();\n }\n\n return rpn;\n }\n\n int evalRPN(vector<string>& rpn) {\n stack<int> st;\n\n for (const auto& token : rpn) {\n if (OPS.find(token) != end(OPS)) {\n if (token == \"UNARY_NEGATE\") {\n int b = st.top();\n st.pop();\n st.push(-b);\n } else {\n int b = st.top();\n st.pop();\n\n int a = 0;\n if (!st.empty()) {\n a = st.top();\n st.pop();\n }\n\n st.push(token[0] == '+' ? a + b : a - b);\n }\n } else {\n st.push(stoi(token));\n }\n } \n\n return st.top();\n }\n\n int calculate(string s) {\n auto rpn = convertToRPN(s);\n return evalRPN(rpn);\n }\n};",
"memory": "49681"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<string> bracket;\n vector<string> given;\n vector<string> reverse;\n string new1=\"\";\n for(int i=0;i<s.size();i++){\n if(s[i]!=' '){\n new1+=s[i];\n }\n }\n s=new1;\n for(int i=0;i<s.size();i++){\n new1=\"\";\n while('0'<=s[i] && s[i]<='9' && i<s.size()){\n new1+=s[i];\n i++;\n }\n if(new1!=\"\"){\n given.push_back(new1);\n if(i==s.size()){\n break;\n }\n i--;\n }\n else{\n if(s[i]=='-'){\n if(i==0){\n given.push_back(\"0\");\n }\n else if(s[i-1]=='('){\n given.push_back(\"0\");\n }\n }\n given.push_back(s[i]+new1);\n }\n }\n for(int i=0;i<given.size();i++){\n if(given[i]!=\"(\" &&given[i]!=\")\" &&given[i]!=\"+\" && given[i]!=\"-\" ){\n reverse.push_back(given[i]);\n }\n else if(given[i]==\"(\" && i!=0){\n bracket.push(given[i-1]);\n }\n else if(given[i]==\")\"){\n if(!bracket.empty()){\n reverse.push_back(bracket.top());\n bracket.pop();\n }\n }\n else if((given[i]==\"+\" || given[i]==\"-\") && given[i+1]!=\"(\"){\n reverse.push_back(given[i+1]);\n reverse.push_back(given[i]);\n i+=1;\n }\n }\n stack<int> cal;\n for(int i=0;i<reverse.size();i++){\n if(reverse[i]!= \"+\" && reverse[i]!=\"-\"){\n cal.push(stoi(reverse[i]));\n }\n if(reverse[i]==\"+\"){\n int x=0;\n int y=0;\n if(!cal.empty()){\n x=cal.top();\n cal.pop();\n }\n if(!cal.empty()){\n y=cal.top();\n cal.pop();\n }\n cal.push(x+y);\n }\n else if(reverse[i]==\"-\"){\n int x=0;\n int y=0;\n if(!cal.empty()){\n x=cal.top();\n cal.pop();\n }\n if(!cal.empty()){\n y=cal.top();\n cal.pop();\n }\n cal.push(-x+y);\n }\n }\n return cal.top();\n }\n};",
"memory": "50618"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<string> bracket;\n vector<string> given;\n vector<string> reverse;\n string new1=\"\";\n for(int i=0;i<s.size();i++){\n if(s[i]!=' '){\n new1+=s[i];\n }\n }\n s=new1;\n for(int i=0;i<s.size();i++){\n new1=\"\";\n while('0'<=s[i] && s[i]<='9' && i<s.size()){\n new1+=s[i];\n i++;\n }\n if(new1!=\"\"){\n given.push_back(new1);\n if(i==s.size()){\n break;\n }\n i--;\n }\n else{\n if(s[i]=='-'){\n if(i==0){\n given.push_back(\"0\");\n }\n else if(s[i-1]=='('){\n given.push_back(\"0\");\n }\n }\n given.push_back(s[i]+new1);\n }\n }\n for(int i=0;i<given.size();i++){\n if(given[i]!=\"(\" &&given[i]!=\")\" &&given[i]!=\"+\" && given[i]!=\"-\" ){\n reverse.push_back(given[i]);\n }\n else if(given[i]==\"(\" && i!=0){\n bracket.push(given[i-1]);\n }\n else if(given[i]==\")\"){\n if(!bracket.empty()){\n reverse.push_back(bracket.top());\n bracket.pop();\n }\n }\n else if((given[i]==\"+\" || given[i]==\"-\") && given[i+1]!=\"(\"){\n reverse.push_back(given[i+1]);\n reverse.push_back(given[i]);\n i+=1;\n }\n }\n stack<int> cal;\n for(int i=0;i<reverse.size();i++){\n if(reverse[i]!= \"+\" && reverse[i]!=\"-\"){\n cal.push(stoi(reverse[i]));\n }\n if(reverse[i]==\"+\"){\n int x=0;\n int y=0;\n\n x=cal.top();\n cal.pop();\n y=cal.top();\n cal.pop();\n cal.push(x+y);\n }\n else if(reverse[i]==\"-\"){\n int x=0;\n int y=0;\n x=cal.top();\n cal.pop();\n y=cal.top();\n cal.pop();\n cal.push(-x+y);\n }\n }\n return cal.top();\n }\n};",
"memory": "51556"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n stack<string> bracket;\n vector<string> given;\n vector<string> reverse;\n string new1=\"\";\n for(int i=0;i<s.size();i++){\n if(s[i]!=' '){\n new1+=s[i];\n }\n }\n s=new1;\n for(int i=0;i<s.size();i++){\n new1=\"\";\n while('0'<=s[i] && s[i]<='9' && i<s.size()){\n new1+=s[i];\n i++;\n }\n if(new1!=\"\"){\n given.push_back(new1);\n if(i==s.size()){\n break;\n }\n i--;\n }\n else{\n if(s[i]=='-'){\n if(i==0){\n given.push_back(\"0\");\n }\n else if(s[i-1]=='('){\n given.push_back(\"0\");\n }\n }\n given.push_back(s[i]+new1);\n }\n }\n for(int i=0;i<given.size();i++){\n if(given[i]!=\"(\" &&given[i]!=\")\" &&given[i]!=\"+\" && given[i]!=\"-\" ){\n reverse.push_back(given[i]);\n }\n else if(given[i]==\"(\" && i!=0){\n bracket.push(given[i-1]);\n }\n else if(given[i]==\")\"){\n if(!bracket.empty()){\n reverse.push_back(bracket.top());\n bracket.pop();\n }\n }\n else if((given[i]==\"+\" || given[i]==\"-\") && given[i+1]!=\"(\"){\n reverse.push_back(given[i+1]);\n reverse.push_back(given[i]);\n i+=1;\n }\n }\n stack<int> cal;\n for(int i=0;i<reverse.size();i++){\n if(reverse[i]!= \"+\" && reverse[i]!=\"-\"){\n cal.push(stoi(reverse[i]));\n }\n if(reverse[i]==\"+\"){\n int x=0;\n int y=0;\n\n x=cal.top();\n cal.pop();\n y=cal.top();\n cal.pop();\n cal.push(x+y);\n }\n else if(reverse[i]==\"-\"){\n int x=0;\n int y=0;\n x=cal.top();\n cal.pop();\n y=cal.top();\n cal.pop();\n cal.push(-x+y);\n }\n }\n return cal.top();\n }\n};",
"memory": "51556"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n bool expNeg = false;\n int calculate(string s) {\n expNeg = false;\n vector<string> expression = getExpression(s);\n vector<string> postfix = getInfixToPostFixExpression(expression);\n // cout << \"hi\\n\";\n return calculatePostFix(postfix) * (expNeg?-1:1);\n }\n \n vector<string> getExpression(string &exp) {\n string s = trimSpace(exp);\n vector<string> expression;\n string cur;\n bool neg = false;\n int i = 0;\n for (; i < s.length(); i++) {\n \n char c = s[i];\n if (c <= '9' && c >= '0') {\n cur.push_back(c);\n if (i == s.length()-1 || (s[i+1]<'0' || s[i+1] > '9')) {\n expression.push_back((neg?\"-\":\"\")+cur);\n cur = \"\";\n neg = false;\n }\n } else if (c == '-' && (expression.empty() || expression.back() == \"(\")){\n expression.push_back(\"-1\");\n expression.push_back(\"*\");\n } else if(c == '+' || c == '-' || c == ')' || c == '(') {\n expression.push_back(string() + c);\n }\n }\n return expression;\n }\n \n string trimSpace(string s) {\n string trimmed = \"\";\n for (char c : s) {\n if (c != ' ' && c != '\\t' && c != '\\r') trimmed.push_back(c);\n }\n return trimmed;\n }\n \n vector<string> getInfixToPostFixExpression(vector<string> &exp) {\n vector<string> postfix;\n stack<string> oprtr;\n for (string s : exp) {\n // cout << s << endl;\n if (s == \"+\" || s == \"-\" || s == \"*\") {\n if (oprtr.empty() || prec(s) > prec(oprtr.top())) {\n oprtr.push(s);\n } else {\n while (!oprtr.empty() && prec(s) <= prec(oprtr.top())) {\n postfix.push_back(oprtr.top());\n oprtr.pop();\n }\n oprtr.push(s);\n }\n } else if (s == \"(\") {\n oprtr.push(\"(\");\n } else if ( s == \")\") {\n while (oprtr.top() != \"(\") {\n postfix.push_back(oprtr.top());\n oprtr.pop();\n }\n oprtr.pop();\n } else {\n postfix.push_back(s);\n }\n }\n while (!oprtr.empty()) {\n postfix.push_back(oprtr.top());\n oprtr.pop();\n }\n return postfix;\n }\n \n int calculatePostFix(vector<string> &exp) {\n stack<int> operand;\n for (string e : exp) {\n // cout << e << endl;\n if (e == \"+\" || e == \"-\" || e == \"*\") {\n int operand2 = operand.top(); operand.pop();\n int operand1 = operand.top(); operand.pop();\n operand.push(exec(operand1, operand2, e));\n } else {\n int val = stoi(e);\n operand.push(val);\n }\n }\n return operand.top();\n }\n \n int exec(int o1, int o2, string oprtr) {\n if (oprtr == \"*\") return o1 * o2;\n if (oprtr == \"+\") return o1 + o2;\n else return o1-o2;\n }\n \n int prec(string s) {\n if (s == \"*\") {\n return 2;\n }\n if (s == \"+\" || s == \"-\") {\n return 1;\n }\n return -1;\n }\n};",
"memory": "52493"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n long long int calc(vector<string> st){\n \n long long int ans=0;\n bool plusCheck=true;\n\n for(int i=st.size()-1;i>=0;i--){\n string x=st[i];\n if(x==\"+\"){\n plusCheck=true;\n }\n else if(x==\"-\"){\n plusCheck=false;\n\n }\n else{\n if(plusCheck){\n ans+=(stoll(x));\n }\n else{\n ans-=(stoll(x));\n }\n\n }\n }\n return ans;\n }\n\n int calculate(string s) {\n int n=s.size();\n vector<string> st;\n int i=0;\n while(i<n){\n string tempo=\"\";\n tempo+=s[i];\n if(tempo==\" \"){\n i++;\n continue;\n }\n if(tempo==\"(\"){\n st.push_back(tempo);\n }\n else if(tempo==\")\"){\n int temp=0;\n vector<string> s2;\n \n while(st.size() and st.back()!=\"(\"){\n string x=st.back();\n st.pop_back();\n s2.push_back(x);\n }\n long long int val=calc(s2);\n st.pop_back();\n string tempo=to_string(val);\n st.push_back(tempo);\n }\n else if(tempo==\"+\" or tempo==\"-\"){\n st.push_back(tempo);\n }\n else{\n string valStorer=\"\";\n valStorer+=tempo;\n \n while(i+1<=n-1 ){\n string tempo=\"\";\n tempo+=s[i+1];\n if(tempo==\" \"){\n i++;\n continue;\n }\n else if(s[i+1]-'0'<=9 and s[i+1]-'0'>=0){\n valStorer+=s[i+1];\n i++;\n }\n else{\n break;\n\n } \n }\n st.push_back(valStorer);\n\n }\n\n i++;\n }\n\n vector<string> s2;\n while(st.size()){\n string temp=st.back();\n st.pop_back();\n s2.push_back(temp);\n\n }\n int ans=calc(s2);\n return ans;\n\n return 0;\n \n }\n};",
"memory": "52493"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n long long int calc(vector<string> st){\n for(auto x:st){\n cout<<x<<\" \";\n }\n cout<<endl;\n long long int ans=0;\n bool plusCheck=true;\n\n for(int i=st.size()-1;i>=0;i--){\n string x=st[i];\n if(x==\"+\"){\n plusCheck=true;\n }\n else if(x==\"-\"){\n plusCheck=false;\n\n }\n else{\n if(plusCheck){\n ans+=(stoll(x));\n }\n else{\n ans-=(stoll(x));\n }\n\n }\n }\n return ans;\n }\n\n int calculate(string s) {\n int n=s.size();\n vector<string> st;\n int i=0;\n \n // st.push_back(\"hello\");\n\n while(i<n){\n string tempo=\"\";\n tempo+=s[i];\n if(tempo==\" \"){\n i++;\n continue;\n }\n if(tempo==\"(\"){\n st.push_back(tempo);\n }\n else if(tempo==\")\"){\n int temp=0;\n vector<string> s2;\n \n while(st.size() and st.back()!=\"(\"){\n string x=st.back();\n st.pop_back();\n s2.push_back(x);\n }\n long long int val=calc(s2);\n st.pop_back();\n string tempo=to_string(val);\n st.push_back(tempo);\n }\n else if(tempo==\"+\" or tempo==\"-\"){\n st.push_back(tempo);\n }\n else{\n string valStorer=\"\";\n valStorer+=tempo;\n \n while(i+1<=n-1 ){\n string tempo=\"\";\n tempo+=s[i+1];\n cout<<\"tempo\"<<tempo<<endl;\n if(tempo==\" \"){\n i++;\n continue;\n }\n else if(s[i+1]-'0'<=9 and s[i+1]-'0'>=0){\n valStorer+=s[i+1];\n i++;\n }\n else{\n break;\n\n }\n \n \n }\n st.push_back(valStorer);\n\n }\n\n i++;\n }\n\n vector<string> s2;\n while(st.size()){\n string temp=st.back();\n st.pop_back();\n s2.push_back(temp);\n\n }\n int ans=calc(s2);\n return ans;\n\n return 0;\n \n }\n};",
"memory": "53431"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int helper(vector<string> s) {\n int sum = 0;\n bool add = !(s[0] == \"-\");\n for (auto &c: s) {\n bool flag = (c[0] == '-' && c.size()>1);\n if (c == \" \")\n continue;\n else if (std::all_of(c.begin(), c.end(), ::isdigit) || flag) {\n sum += add ? stoi(c) : stoi(c) * -1;\n } else if (c == \"+\") {\n add = true;\n } else if (c == \"-\") {\n add = false;\n }\n }\n return sum;\n}\n\nint calculate(string s) {\n stack<string> st;\n int res = 0;\n vector<string> tmp2;\n for (int i = 0; i < s.size(); i++) {\n char c = s[i];\n if (c == ' ')\n continue;\n if (c == ')') {\n vector<string> tmp;\n while (st.top() != \"(\") {\n tmp.emplace_back(st.top());\n st.pop();\n }\n st.pop();\n reverse(tmp.begin(), tmp.end());\n int sum = helper(tmp);\n cout << \"sum=\" << sum <<endl;\n st.push(to_string(sum));\n continue;\n }\n if (isdigit(c)) {\n string tmp3;\n int j = i;\n while (isdigit(s[j])){\n tmp3.push_back(s[j]);\n j++;\n }\n i = j - 1;\n st.push(tmp3);\n continue;\n }\n string tmp4;\n tmp4.push_back(c);\n st.push(tmp4);\n }\n while (!st.empty()) {\n tmp2.emplace_back(st.top());\n st.pop();\n }\n reverse(tmp2.begin(), tmp2.end());\n for (auto it =tmp2.begin(); it!=tmp2.end();it++)\n cout << *it<<endl;\n res = helper(tmp2);\n return res;\n}\n};",
"memory": "54368"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int process(vector<string> v) {\n int sol = 0;\n int i = 0;\n while (i < v.size()) {\n if (v[i] == \"+\") {\n sol = sol + stoi(v[i + 1]);\n i += 2;\n } else if (v[i] == \"-\") {\n sol = sol - stoi(v[i + 1]);\n i += 2;\n } else {\n sol += stoi(v[i]);\n i++;\n }\n }\n return sol;\n }\n int eval(string s, int i, int j) {\n stack<string> st;\n string num;\n while (i <= j) {\n if (s[i] >= '0' && s[i] <= '9') {\n num.push_back(s[i]);\n } else {\n if(num.size() > 0) {\n st.push(num);\n num.clear();\n }\n if (s[i] == ')') {\n int sol = 0;\n vector<string> v;\n while (st.top() != \"(\") {\n v.push_back(st.top());\n st.pop();\n }\n st.pop();\n reverse(v.begin(), v.end());\n st.push(to_string(process(v)));\n }\n else if(!isspace(s[i])) {\n string ch;\n ch.push_back(s[i]);\n st.push(ch);\n }\n }\n i++;\n }\n return stoi(st.top());\n }\n int calculate(string s) {\n s = \"(\" + s + \")\";\n int n = s.size();\n return eval(s, 0, n - 1);\n }\n};",
"memory": "55306"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n vector<string> tokenize(string s) {\n std::vector<string> result;\n\n bool is_bin_sub = false;\n \n for (int cursor = 0; cursor < s.length();) {\n\n // Skip preceeding whitespace.\n while (cursor < s.length() && s.at(cursor) == ' ') {\n cursor++;\n }\n if (cursor == s.length()) break;\n\n // Parse a token.\n string token;\n char c = s.at(cursor);\n if (c == '+' || c == '-' || c == '(' || c == ')') {\n if (c == '-') {\n token = is_bin_sub ? \"-\" : \"~\";\n } else {\n token = c;\n }\n cursor++;\n is_bin_sub = (c == ')');\n } else if (isdigit(c)) {\n while (isdigit(c)) {\n token += c;\n cursor++;\n if (cursor >= s.length()) break;\n c = s.at(cursor);\n }\n is_bin_sub = true;\n }\n\n result.push_back(token);\n }\n \n return result;\n }\n\n // shunting-yard\n vector<string> toRPN(const vector<string> tokens) {\n stack<string> operators;\n vector<string> output;\n for (string token : tokens) {\n if (token == \"+\" || token == \"-\" || token == \"~\") {\n // Note the real shunting-yard logic is more complicated, but we only have + and -.\n while (!operators.empty() && operators.top() != \"(\") {\n output.push_back(operators.top());\n operators.pop();\n }\n operators.push(token);\n } else if (token == \"(\") {\n operators.push(token);\n } else if (token == \")\") {\n while (operators.top() != \"(\") {\n output.push_back(operators.top());\n operators.pop();\n }\n operators.pop(); // (\n } else {\n output.push_back(token);\n }\n }\n while (!operators.empty()) {\n output.push_back(operators.top());\n operators.pop();\n }\n return output;\n }\n\n int evalRPN(vector<string>& tokens) {\n stack<int> operands;\n for (string& token : tokens) {\n if (token == \"+\") {\n int b = operands.top();\n operands.pop();\n int a = operands.top();\n operands.pop();\n operands.push(a + b);\n } else if (token == \"-\") {\n int b = operands.top();\n operands.pop();\n int a = operands.top();\n operands.pop();\n operands.push(a - b);\n } else if (token == \"~\") {\n int a = operands.top();\n operands.pop();\n operands.push(-a);\n } else {\n operands.push(stoi(token));\n }\n }\n return operands.top();\n }\n\n int calculate(string s) {\n auto tokens = tokenize(s);\n auto rpn = toRPN(tokens);\n return evalRPN(rpn);\n }\n\n\n};",
"memory": "56243"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\nclass Solution {\npublic:\n bool isNum(char c) {\n return '0' <= c && c <= '9';\n }\n\n vector<string> createTokens(string s) {\n vector<string> tokens;\n \n int start = 0, end = 0;\n if (s[0] == '-') {\n tokens.push_back(\"0\");\n }\n while (end < s.length()) {\n if (s[start] == ' ') {\n start++;\n end++;\n continue;\n }\n if (!isNum(s[start])) {\n if (s[start] == '-' && tokens.back() == \"(\") {\n tokens.push_back(\"0\");\n }\n tokens.push_back(s.substr(start, 1));\n start++;\n end++;\n continue;\n }\n if (isNum(s[start]) && isNum(s[end])) {\n end++;\n continue;\n }\n if (isNum(s[start]) && !isNum(s[end])) {\n tokens.push_back(s.substr(start, end - start));\n start = end;\n continue;\n }\n }\n if (start < s.length()) {\n tokens.push_back(s.substr(start, end - start));\n }\n\n return tokens;\n }\n\n vector<string> createReversePolishNotation(vector<string> tokens) {\n vector<string> reversePolishTokens;\n stack<string> operators;\n \n for (string token : tokens) {\n if (isNum(token[0])) {\n reversePolishTokens.push_back(token);\n }\n else if (token == \"(\") {\n operators.push(token);\n }\n else if (token == \")\") {\n while (operators.top() != \"(\") {\n reversePolishTokens.push_back(operators.top());\n operators.pop();\n }\n operators.pop();\n }\n else if (token == \"+\" || token == \"-\") {\n while (!operators.empty() && operators.top() != \"(\") {\n reversePolishTokens.push_back(operators.top());\n operators.pop();\n }\n operators.push(token);\n }\n }\n while (!operators.empty()) {\n reversePolishTokens.push_back(operators.top());\n operators.pop();\n }\n\n return reversePolishTokens;\n }\n\n int evaluateReversePolishNotation(vector<string> reversePolishTokens) {\n stack<string> operands;\n for (string token : reversePolishTokens) {\n if (isNum(token[0])) {\n operands.push(token);\n continue;\n }\n int num2 = stoi(operands.top());\n operands.pop();\n int num1 = stoi(operands.top());\n operands.pop();\n if (token == \"+\") {\n operands.push(to_string(num1 + num2));\n }\n else if (token == \"-\") {\n operands.push(to_string(num1 - num2));\n }\n }\n\n return stoi(operands.top());\n }\n\n int calculate(string s) {\n vector<string> tokens;\n vector<string> reversePolishTokens;\n int res;\n\n tokens = createTokens(s);\n // std::cout << \"Created Tokens\\n\";\n // for (auto token : tokens) {\n // std::cout << token << \", \";\n // }\n // std::cout << std::endl;\n reversePolishTokens = createReversePolishNotation(tokens);\n // std::cout << \"Created Reverse Polish Notation\\n\";\n // for (auto token : reversePolishTokens) {\n // std::cout << token << \", \";\n // }\n // std::cout << std::endl;\n res = evaluateReversePolishNotation(reversePolishTokens);\n\n return res;\n }\n};",
"memory": "61868"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n bool isNum(char c) {\n return '0' <= c && c <= '9';\n }\n\n vector<string> createTokens(string s) {\n vector<string> tokens;\n \n int start = 0, end = 0;\n if (s[0] == '-') {\n tokens.push_back(\"0\");\n }\n while (end < s.length()) {\n if (s[start] == ' ') {\n start++;\n end++;\n continue;\n }\n if (!isNum(s[start])) {\n if (s[start] == '-' && tokens.back() == \"(\") {\n tokens.push_back(\"0\");\n }\n tokens.push_back(s.substr(start, 1));\n start++;\n end++;\n continue;\n }\n if (isNum(s[start]) && isNum(s[end])) {\n end++;\n continue;\n }\n if (isNum(s[start]) && !isNum(s[end])) {\n tokens.push_back(s.substr(start, end - start));\n start = end;\n continue;\n }\n }\n if (start < s.length()) {\n tokens.push_back(s.substr(start, end - start));\n }\n\n return tokens;\n }\n\n vector<string> createReversePolishNotation(vector<string> tokens) {\n vector<string> reversePolishTokens;\n stack<string> operators;\n \n for (string token : tokens) {\n if (isNum(token[0])) {\n reversePolishTokens.push_back(token);\n }\n else if (token == \"(\") {\n operators.push(token);\n }\n else if (token == \")\") {\n while (operators.top() != \"(\") {\n reversePolishTokens.push_back(operators.top());\n operators.pop();\n }\n operators.pop();\n }\n else if (token == \"+\" || token == \"-\") {\n while (!operators.empty() && operators.top() != \"(\") {\n reversePolishTokens.push_back(operators.top());\n operators.pop();\n }\n operators.push(token);\n }\n }\n while (!operators.empty()) {\n reversePolishTokens.push_back(operators.top());\n operators.pop();\n }\n\n return reversePolishTokens;\n }\n\n int evaluateReversePolishNotation(vector<string> reversePolishTokens) {\n stack<string> operands;\n for (string token : reversePolishTokens) {\n if (isNum(token[0])) {\n operands.push(token);\n continue;\n }\n int num2 = stoi(operands.top());\n operands.pop();\n int num1 = stoi(operands.top());\n operands.pop();\n if (token == \"+\") {\n operands.push(to_string(num1 + num2));\n }\n else if (token == \"-\") {\n operands.push(to_string(num1 - num2));\n }\n }\n\n return stoi(operands.top());\n }\n\n int calculate(string s) {\n vector<string> tokens;\n vector<string> reversePolishTokens;\n int res;\n\n tokens = createTokens(s);\n // std::cout << \"Created Tokens\\n\";\n // for (auto token : tokens) {\n // std::cout << token << \", \";\n // }\n // std::cout << std::endl;\n reversePolishTokens = createReversePolishNotation(tokens);\n // std::cout << \"Created Reverse Polish Notation\\n\";\n // for (auto token : reversePolishTokens) {\n // std::cout << token << \", \";\n // }\n // std::cout << std::endl;\n res = evaluateReversePolishNotation(reversePolishTokens);\n\n return res;\n }\n};",
"memory": "61868"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\nclass Solution {\npublic:\n bool isNum(char c) {\n return '0' <= c && c <= '9';\n }\n\n vector<string> createTokens(string s) {\n vector<string> tokens;\n \n int start = 0, end = 0;\n if (s[0] == '-') {\n tokens.push_back(\"0\");\n }\n while (end < s.length()) {\n if (s[start] == ' ') {\n start++;\n end++;\n continue;\n }\n if (!isNum(s[start])) {\n if (s[start] == '-' && tokens.back() == \"(\") {\n tokens.push_back(\"0\");\n }\n tokens.push_back(s.substr(start, 1));\n start++;\n end++;\n continue;\n }\n if (isNum(s[start]) && isNum(s[end])) {\n end++;\n continue;\n }\n if (isNum(s[start]) && !isNum(s[end])) {\n tokens.push_back(s.substr(start, end - start));\n start = end;\n continue;\n }\n }\n if (start < s.length()) {\n tokens.push_back(s.substr(start, end - start));\n }\n\n return tokens;\n }\n\n vector<string> createReversePolishNotation(vector<string> tokens) {\n vector<string> reversePolishTokens;\n stack<string> operators;\n \n for (string token : tokens) {\n if (isNum(token[0])) {\n reversePolishTokens.push_back(token);\n }\n else if (token == \"(\") {\n operators.push(token);\n }\n else if (token == \")\") {\n while (operators.top() != \"(\") {\n reversePolishTokens.push_back(operators.top());\n operators.pop();\n }\n operators.pop();\n }\n else if (token == \"+\" || token == \"-\") {\n while (!operators.empty() && operators.top() != \"(\") {\n reversePolishTokens.push_back(operators.top());\n operators.pop();\n }\n operators.push(token);\n }\n }\n while (!operators.empty()) {\n reversePolishTokens.push_back(operators.top());\n operators.pop();\n }\n\n return reversePolishTokens;\n }\n\n int evaluateReversePolishNotation(vector<string> reversePolishTokens) {\n stack<string> operands;\n for (string token : reversePolishTokens) {\n if (isNum(token[0])) {\n operands.push(token);\n continue;\n }\n int num2 = stoi(operands.top());\n operands.pop();\n int num1 = stoi(operands.top());\n operands.pop();\n if (token == \"+\") {\n operands.push(to_string(num1 + num2));\n }\n else if (token == \"-\") {\n operands.push(to_string(num1 - num2));\n }\n }\n\n return stoi(operands.top());\n }\n\n int calculate(string s) {\n vector<string> tokens;\n vector<string> reversePolishTokens;\n int res;\n\n tokens = createTokens(s);\n std::cout << \"Created Tokens\\n\";\n for (auto token : tokens) {\n std::cout << token << \", \";\n }\n std::cout << std::endl;\n reversePolishTokens = createReversePolishNotation(tokens);\n std::cout << \"Created Reverse Polish Notation\\n\";\n for (auto token : reversePolishTokens) {\n std::cout << token << \", \";\n }\n std::cout << std::endl;\n res = evaluateReversePolishNotation(reversePolishTokens);\n\n return res;\n }\n};",
"memory": "62806"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class myexception : public exception{\n virtual const char* what() const throw(){\n return \"zero divisor\";\n } \n}myex;\nclass Solution {\npublic:\n // int calculate(const string& s) {\n // long res = 0, num = 0, n = s.size();\n // vector<int> sign(2,1);\n // for(int i=0; i<n; ++i){\n // if(isdigit(s[i])){\n // while(i<n && isdigit(s[i])) num = num*10+s[i++]-'0';\n // --i;\n // res += num*sign.back();\n // num = 0;\n // sign.pop_back();\n // }else if(s[i] == ')') sign.pop_back();\n // else if(s[i] != ' ') sign.push_back(sign.back()*(s[i]=='-' ? -1 : 1));\n // }\n // return res;\n // }\n \n \n // // Solution 1: recursive\n // int calculate(const string& s) {\n // long n = s.size(), num = 0, t = 0, res = 0;\n // char op = '+'; // last/prev operator\n // for (int i = 0; i < n; ++i) {\n // char c = s[i];\n // if (c == '(') {\n // int j = i, cnt = 0;\n // for (; i < n; ++i) \n // if(!(cnt += s[i]=='(' ? 1 : s[i]==')' ? -1 : 0)) break;\n // num = calculate(s.substr(j + 1, i - j - 1));\n // }else if (isdigit(c)) num = 10*num + c - '0';\n // if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) {\n // t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : t/num;\n // if (c == '+' || c == '-' || i == n - 1) {\n // res += t;\n // t = 0;\n // }\n // op = c;\n // num = 0;\n // }\n // }\n // return res;\n // }\n \n int calculate(const string& s) {\n long res = 0;\n char op = '+';\n for(long i=0, n=s.size(), t=0, num=0; i<n; ++i){\n char c = s[i];\n if(c == '('){\n int cnt = 0, start = i+1;\n for(; i<n; ++i)\n if(!(cnt+=(s[i]=='(' ? 1 : s[i]==')' ? -1 : 0))) break;\n num = calculate(s.substr(start, i-start));\n }else if(isdigit(c)) num = 10*num + c-'0';\n if(c=='+' || c=='-' || c=='*' || c=='/' || i==n-1){\n // try{\n // t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : (num ? t/num : throw myex);\n // }catch(exception& e){\n // cout << e.what() << endl;\n // }\n t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : (num ? t/num : INT_MAX);\n if(c=='+' || c=='-' || i==n-1) res += t, t = 0;\n num = 0;\n op = c;\n }\n }\n return res;\n }\n \n// int calculate(const string& s) {\n// long res = 0, t = 0, num = 0;// t: stk's top element, num: current element\n// char op = '+';\n// for(int i=0, n=s.size(); i<n; ++i){\n// char c = s[i];\n// if(c=='('){\n// // int cnt = 1, start = ++i;\n// // while(i<n && cnt>0) cnt += (s[i]=='(' ? 1 : s[i]==')' ? -1 : 0), ++i;\n// // --i; // use while do --i, use for break no need to do --i;\n// // num = calculate(s.substr(start, i-start));\n \n// int cnt = 0, start = i+1;\n// for(; i<n; ++i)\n// if(!(cnt += (s[i]=='(' ? 1 : s[i]==')' ? -1 : 0))) break;\n// num = calculate(s.substr(start, i-start));\n// }else if(isdigit(c)) num = 10*num+c-'0';\n// if(c=='+' || c=='-' || c=='*' || c=='/' || i==n-1){ // NOTE: !!! No else before if\n// t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : (num ? t/num : INT_MAX);\n// if(c=='+' || c=='-' || i==n-1){\n// res += t;\n// t = 0;\n// }\n// num = 0;\n// op = c;\n// }\n// }\n// return res;\n// }\n \n \n\n \n \n \n // void eval(stack<int>& stk, const char& op, int val){\n // stk.push(op=='+' ? val : op=='-' ? -val : op=='*' ? stk.top()*val : (val ? stk.top()/val : INT_MAX));\n // }\n // // return <val, index>\n // pair<int,int> cal(const string& s){\n // char op = '+'; // lastOp\n // long num = 0;\n // stack<int> stk;\n // for(int i=0, n=s.size(); i<n; ++i){\n // char c = s[i];\n // if(isdigit(c)) num = 10*num+c-'0';\n // else if(c=='+' || c=='-' || c=='*' || c=='/'){\n // eval(stk, op, num);\n // op = c;\n // num = 0;\n // }else if(c=='('){\n // auto r = cal(s.substr(i+1));\n // num = r.first;\n // i += r.second;\n // }else if(c==')'){\n // eval(stk, op, num);\n // int sum = 0;\n // while(!stk.empty()) sum += stk.top(), stk.pop();\n // return {sum, i+1};\n // }\n // }\n // eval(stk, op, num);\n // int sum = 0;\n // while(!stk.empty()) sum += stk.top(), stk.pop();\n // return {sum, s.size()};\n // }\n // // Solution 2:\n // int calculate(const string& s) {\n // return cal(s).first;\n // }\n \n\n \n // unordered_map<char, int> m = {\n // {'(', 3},\n // {')', 3},\n // {'*', 2},\n // {'/', 2},\n // {'+', 1},\n // {'-', 1}\n // };\n // bool isLowerThan(const char& op1, const char& op2){\n // return m[op2]!=3 && m[op1]<=m[op2];\n // }\n // void handle(stack<int>& stk, stack<char>& op){\n // char c = op.top(); op.pop();\n // if(stk.size()==1){stk.top()*=(c=='-' ? -1 : 1); return;}\n // int second = stk.top(); stk.pop();\n // int first = stk.top(); stk.pop();\n // stk.push(c=='+' ? first+second : c=='-' ? first-second : c=='*' ? first*second : second ? first/second : INT_MAX);\n // }\n // int calculate(const string& s){\n // stack<int> stk;\n // stack<char> op;\n // for(int i=0, n=s.size(); i<n; ++i){\n // if(s[i]=='(') op.push('(');\n // else if(s[i]==')'){\n // while(op.top()!='(') handle(stk,op);\n // op.pop();\n // }else if(isdigit(s[i])){\n // long num = 0;\n // while(i<n && isdigit(s[i])) num=10*num+s[i++]-'0';\n // --i;\n // stk.push(num);\n // }else if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/'){\n // while(!op.empty() && isLowerThan(s[i], op.top())) handle(stk,op);\n // op.push(s[i]);\n // }\n // }\n // while(!op.empty()) handle(stk, op);\n // return stk.top();\n // }\n \n \n// unordered_map<char, int> m = { // can't handle 3-(-2)\n// {'(', 3},\n// {')', 3},\n// {'*', 2},\n// {'/', 2},\n// {'+', 1},\n// {'-', 1},\n// };\n// // op1<=op2\n// bool isLowerEqualThan(const char& op1, const char& op2){\n// return m[op2]!=3 && m[op1]<=m[op2];\n// }\n// void handle(stack<int>& stk, stack<char>& op){\n// const char c = op.top(); op.pop();\n// if(stk.size()==1) { // handle (-2)+1 or -2+1 // Can't handle 3-(-2)\n// stk.top()*=(c=='-' ? -1 : 1);\n// // cout << stk.top() << endl;\n// return;\n// }\n// int second = stk.top(); stk.pop();\n// int first = stk.top(); stk.pop();\n// stk.push(c=='+' ? first+second : c=='-' ? first-second : c=='*' ? first*second : !second ? INT_MAX : first/second);\n// }\n// int calculate(const string& s) { \n// stack<int> stk;\n// stack<char> op;\n// for(int i=0, n=s.size(); i<n; ++i){\n// if(s[i]=='(') op.push('(');\n// else if(s[i]==')'){\n// while(op.top()!='(') handle(stk, op);\n// op.pop();\n// }else if(isdigit(s[i])){\n// char c = op.top(); op.pop();\n \n// long num = 0, sign = \n// while(i<n && isdigit(s[i])) num = 10*num+s[i++]-'0';\n// --i;\n// char c = '\\0';\n// if(!op.empty() && op.top()=='-') c = op.top(), op.pop();\n// if(c=='-' && (!op.empty() && op.top()=='(')) stk.push(-num);\n// else op.push('-'), stk.push(num);\n// // stk.push(num);\n// }else if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/'){\n// while(!op.empty() && isLowerEqualThan(s[i],op.top())) handle(stk, op);\n// op.push(s[i]);\n// }\n// }\n// while(!op.empty()) handle(stk, op);\n// return stk.top();\n// }\n \n \n// /*\n// int res = 0, n = s.size(), num = 0;\n// vector<int> sign(2,1);\n// for(int i=0; i<n; ++i){\n// if(isdigit(s[i])){\n// while(i<n && isdigit(s[i])) num=10*num+s[i++]-'0';\n// res += num*sign.back();\n// sign.pop_back();\n// num = 0;\n// --i;\n// }else if(s[i] == ')') sign.pop_back();\n// else if(s[i] != ' ') sign.push_back(sign.back()*(s[i]=='-' ? -1 : 1));\n// }\n// return res;*/\n \n \n// /*int res = 0, n = s.size(), num = 0;\n// vector<int> sign (2, 1);\n// for(int i=0; i<n; ++i){\n// if(isdigit(s[i])){\n// num = 0;\n// while(i<n && isdigit(s[i])) num = num*10 + s[i++]-'0';\n// --i;\n// res += sign.back()* num;\n// sign.pop_back();\n// }else if(s[i] == ')') sign.pop_back();\n// else if(s[i] != ' ') sign.push_back(sign.back()*(s[i] == '-' ? -1 : 1));\n// }\n// return res;*/\n \n \n// /*int res = 0;\n// vector<int> signs(2,1);\n// for (int i=0; i<s.size(); ++i) {\n// char c = s[i];\n// if (isdigit(c)) { // same as: if (c >= '0') {\n// int number = 0;\n// while (i < s.size() && s[i] >= '0') number = 10 * number + s[i++] - '0';\n// --i;\n// res += signs.back() * number;\n// signs.pop_back();\n// } else if (c == ')') signs.pop_back();\n// else if (c != ' ') signs.push_back(signs.back() * (c == '-' ? -1 : 1));\n// }\n// return res;*/\n// }\n};",
"memory": "63743"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class myexception : public exception{\n virtual const char* what() const throw(){\n return \"zero divisor\";\n } \n}myex;\nclass Solution {\npublic:\n // int calculate(const string& s) {\n // long res = 0, num = 0, n = s.size();\n // vector<int> sign(2,1);\n // for(int i=0; i<n; ++i){\n // if(isdigit(s[i])){\n // while(i<n && isdigit(s[i])) num = num*10+s[i++]-'0';\n // --i;\n // res += num*sign.back();\n // num = 0;\n // sign.pop_back();\n // }else if(s[i] == ')') sign.pop_back();\n // else if(s[i] != ' ') sign.push_back(sign.back()*(s[i]=='-' ? -1 : 1));\n // }\n // return res;\n // }\n \n \n // // Solution 1: recursive\n // int calculate(const string& s) {\n // long n = s.size(), num = 0, t = 0, res = 0;\n // char op = '+'; // last/prev operator\n // for (int i = 0; i < n; ++i) {\n // char c = s[i];\n // if (c == '(') {\n // int j = i, cnt = 0;\n // for (; i < n; ++i) \n // if(!(cnt += s[i]=='(' ? 1 : s[i]==')' ? -1 : 0)) break;\n // num = calculate(s.substr(j + 1, i - j - 1));\n // }else if (isdigit(c)) num = 10*num + c - '0';\n // if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) {\n // t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : t/num;\n // if (c == '+' || c == '-' || i == n - 1) {\n // res += t;\n // t = 0;\n // }\n // op = c;\n // num = 0;\n // }\n // }\n // return res;\n // }\n \n int calculate(const string& s) {\n long res = 0;\n char op = '+';\n for(long i=0, n=s.size(), t=0, num=0; i<n; ++i){\n char c = s[i];\n if(c == '('){\n int cnt = 0, start = i+1;\n for(; i<n; ++i)\n if(!(cnt+=(s[i]=='(' ? 1 : s[i]==')' ? -1 : 0))) break;\n num = calculate(s.substr(start, i-start));\n }else if(isdigit(c)) num = 10*num + c-'0';\n if(c=='+' || c=='-' || c=='*' || c=='/' || i==n-1){\n // try{\n // t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : (num ? t/num : throw myex);\n // }catch(exception& e){\n // cout << e.what() << endl;\n // }\n t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : (num ? t/num : INT_MAX);\n if(c=='+' || c=='-' || i==n-1) res += t, t = 0;\n num = 0;\n op = c;\n }\n }\n return res;\n }\n \n// int calculate(const string& s) {\n// long res = 0, t = 0, num = 0;// t: stk's top element, num: current element\n// char op = '+';\n// for(int i=0, n=s.size(); i<n; ++i){\n// char c = s[i];\n// if(c=='('){\n// // int cnt = 1, start = ++i;\n// // while(i<n && cnt>0) cnt += (s[i]=='(' ? 1 : s[i]==')' ? -1 : 0), ++i;\n// // --i; // use while do --i, use for break no need to do --i;\n// // num = calculate(s.substr(start, i-start));\n \n// int cnt = 0, start = i+1;\n// for(; i<n; ++i)\n// if(!(cnt += (s[i]=='(' ? 1 : s[i]==')' ? -1 : 0))) break;\n// num = calculate(s.substr(start, i-start));\n// }else if(isdigit(c)) num = 10*num+c-'0';\n// if(c=='+' || c=='-' || c=='*' || c=='/' || i==n-1){ // NOTE: !!! No else before if\n// t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : (num ? t/num : INT_MAX);\n// if(c=='+' || c=='-' || i==n-1){\n// res += t;\n// t = 0;\n// }\n// num = 0;\n// op = c;\n// }\n// }\n// return res;\n// }\n \n \n\n \n \n \n // void eval(stack<int>& stk, const char& op, int val){\n // stk.push(op=='+' ? val : op=='-' ? -val : op=='*' ? stk.top()*val : (val ? stk.top()/val : INT_MAX));\n // }\n // // return <val, index>\n // pair<int,int> cal(const string& s){\n // char op = '+'; // lastOp\n // long num = 0;\n // stack<int> stk;\n // for(int i=0, n=s.size(); i<n; ++i){\n // char c = s[i];\n // if(isdigit(c)) num = 10*num+c-'0';\n // else if(c=='+' || c=='-' || c=='*' || c=='/'){\n // eval(stk, op, num);\n // op = c;\n // num = 0;\n // }else if(c=='('){\n // auto r = cal(s.substr(i+1));\n // num = r.first;\n // i += r.second;\n // }else if(c==')'){\n // eval(stk, op, num);\n // int sum = 0;\n // while(!stk.empty()) sum += stk.top(), stk.pop();\n // return {sum, i+1};\n // }\n // }\n // eval(stk, op, num);\n // int sum = 0;\n // while(!stk.empty()) sum += stk.top(), stk.pop();\n // return {sum, s.size()};\n // }\n // // Solution 2:\n // int calculate(const string& s) {\n // return cal(s).first;\n // }\n \n\n \n // unordered_map<char, int> m = {\n // {'(', 3},\n // {')', 3},\n // {'*', 2},\n // {'/', 2},\n // {'+', 1},\n // {'-', 1}\n // };\n // bool isLowerThan(const char& op1, const char& op2){\n // return m[op2]!=3 && m[op1]<=m[op2];\n // }\n // void handle(stack<int>& stk, stack<char>& op){\n // char c = op.top(); op.pop();\n // if(stk.size()==1){stk.top()*=(c=='-' ? -1 : 1); return;}\n // int second = stk.top(); stk.pop();\n // int first = stk.top(); stk.pop();\n // stk.push(c=='+' ? first+second : c=='-' ? first-second : c=='*' ? first*second : second ? first/second : INT_MAX);\n // }\n // int calculate(const string& s){\n // stack<int> stk;\n // stack<char> op;\n // for(int i=0, n=s.size(); i<n; ++i){\n // if(s[i]=='(') op.push('(');\n // else if(s[i]==')'){\n // while(op.top()!='(') handle(stk,op);\n // op.pop();\n // }else if(isdigit(s[i])){\n // long num = 0;\n // while(i<n && isdigit(s[i])) num=10*num+s[i++]-'0';\n // --i;\n // stk.push(num);\n // }else if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/'){\n // while(!op.empty() && isLowerThan(s[i], op.top())) handle(stk,op);\n // op.push(s[i]);\n // }\n // }\n // while(!op.empty()) handle(stk, op);\n // return stk.top();\n // }\n \n \n// unordered_map<char, int> m = { // can't handle 3-(-2)\n// {'(', 3},\n// {')', 3},\n// {'*', 2},\n// {'/', 2},\n// {'+', 1},\n// {'-', 1},\n// };\n// // op1<=op2\n// bool isLowerEqualThan(const char& op1, const char& op2){\n// return m[op2]!=3 && m[op1]<=m[op2];\n// }\n// void handle(stack<int>& stk, stack<char>& op){\n// const char c = op.top(); op.pop();\n// if(stk.size()==1) { // handle (-2)+1 or -2+1 // Can't handle 3-(-2)\n// stk.top()*=(c=='-' ? -1 : 1);\n// // cout << stk.top() << endl;\n// return;\n// }\n// int second = stk.top(); stk.pop();\n// int first = stk.top(); stk.pop();\n// stk.push(c=='+' ? first+second : c=='-' ? first-second : c=='*' ? first*second : !second ? INT_MAX : first/second);\n// }\n// int calculate(const string& s) { \n// stack<int> stk;\n// stack<char> op;\n// for(int i=0, n=s.size(); i<n; ++i){\n// if(s[i]=='(') op.push('(');\n// else if(s[i]==')'){\n// while(op.top()!='(') handle(stk, op);\n// op.pop();\n// }else if(isdigit(s[i])){\n// char c = op.top(); op.pop();\n \n// long num = 0, sign = \n// while(i<n && isdigit(s[i])) num = 10*num+s[i++]-'0';\n// --i;\n// char c = '\\0';\n// if(!op.empty() && op.top()=='-') c = op.top(), op.pop();\n// if(c=='-' && (!op.empty() && op.top()=='(')) stk.push(-num);\n// else op.push('-'), stk.push(num);\n// // stk.push(num);\n// }else if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/'){\n// while(!op.empty() && isLowerEqualThan(s[i],op.top())) handle(stk, op);\n// op.push(s[i]);\n// }\n// }\n// while(!op.empty()) handle(stk, op);\n// return stk.top();\n// }\n \n \n// /*\n// int res = 0, n = s.size(), num = 0;\n// vector<int> sign(2,1);\n// for(int i=0; i<n; ++i){\n// if(isdigit(s[i])){\n// while(i<n && isdigit(s[i])) num=10*num+s[i++]-'0';\n// res += num*sign.back();\n// sign.pop_back();\n// num = 0;\n// --i;\n// }else if(s[i] == ')') sign.pop_back();\n// else if(s[i] != ' ') sign.push_back(sign.back()*(s[i]=='-' ? -1 : 1));\n// }\n// return res;*/\n \n \n// /*int res = 0, n = s.size(), num = 0;\n// vector<int> sign (2, 1);\n// for(int i=0; i<n; ++i){\n// if(isdigit(s[i])){\n// num = 0;\n// while(i<n && isdigit(s[i])) num = num*10 + s[i++]-'0';\n// --i;\n// res += sign.back()* num;\n// sign.pop_back();\n// }else if(s[i] == ')') sign.pop_back();\n// else if(s[i] != ' ') sign.push_back(sign.back()*(s[i] == '-' ? -1 : 1));\n// }\n// return res;*/\n \n \n// /*int res = 0;\n// vector<int> signs(2,1);\n// for (int i=0; i<s.size(); ++i) {\n// char c = s[i];\n// if (isdigit(c)) { // same as: if (c >= '0') {\n// int number = 0;\n// while (i < s.size() && s[i] >= '0') number = 10 * number + s[i++] - '0';\n// --i;\n// res += signs.back() * number;\n// signs.pop_back();\n// } else if (c == ')') signs.pop_back();\n// else if (c != ' ') signs.push_back(signs.back() * (c == '-' ? -1 : 1));\n// }\n// return res;*/\n// }\n};",
"memory": "64681"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class myexception : public exception{\n virtual const char* what() const throw(){\n return \"zero divisor\";\n } \n}myex;\nclass Solution {\npublic:\n // int calculate(const string& s) {\n // long res = 0, num = 0, n = s.size();\n // vector<int> sign(2,1);\n // for(int i=0; i<n; ++i){\n // if(isdigit(s[i])){\n // while(i<n && isdigit(s[i])) num = num*10+s[i++]-'0';\n // --i;\n // res += num*sign.back();\n // num = 0;\n // sign.pop_back();\n // }else if(s[i] == ')') sign.pop_back();\n // else if(s[i] != ' ') sign.push_back(sign.back()*(s[i]=='-' ? -1 : 1));\n // }\n // return res;\n // }\n \n \n // // Solution 1: recursive\n // int calculate(const string& s) {\n // long n = s.size(), num = 0, t = 0, res = 0;\n // char op = '+'; // last/prev operator\n // for (int i = 0; i < n; ++i) {\n // char c = s[i];\n // if (c == '(') {\n // int j = i, cnt = 0;\n // for (; i < n; ++i) \n // if(!(cnt += s[i]=='(' ? 1 : s[i]==')' ? -1 : 0)) break;\n // num = calculate(s.substr(j + 1, i - j - 1));\n // }else if (isdigit(c)) num = 10*num + c - '0';\n // if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) {\n // t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : t/num;\n // if (c == '+' || c == '-' || i == n - 1) {\n // res += t;\n // t = 0;\n // }\n // op = c;\n // num = 0;\n // }\n // }\n // return res;\n // }\n \n int calculate(const string& s) {\n long res = 0;\n char op = '+';\n for(long i=0, n=s.size(), t=0, num=0; i<n; ++i){\n char c = s[i];\n if(c == '('){\n int cnt = 0, start = i+1;\n for(; i<n; ++i)\n if(!(cnt+=(s[i]=='(' ? 1 : s[i]==')' ? -1 : 0))) break;\n num = calculate(s.substr(start, i-start));\n }else if(isdigit(c)) num = 10*num + c-'0';\n if(c=='+' || c=='-' || c=='*' || c=='/' || i==n-1){\n // try{\n // t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : (num ? t/num : throw myex);\n // }catch(exception& e){\n // cout << e.what() << endl;\n // }\n t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : (num ? t/num : INT_MAX);\n if(c=='+' || c=='-' || i==n-1) res += t, t = 0;\n num = 0;\n op = c;\n }\n }\n return res;\n }\n \n// int calculate(const string& s) {\n// long res = 0, t = 0, num = 0;// t: stk's top element, num: current element\n// char op = '+';\n// for(int i=0, n=s.size(); i<n; ++i){\n// char c = s[i];\n// if(c=='('){\n// // int cnt = 1, start = ++i;\n// // while(i<n && cnt>0) cnt += (s[i]=='(' ? 1 : s[i]==')' ? -1 : 0), ++i;\n// // --i; // use while do --i, use for break no need to do --i;\n// // num = calculate(s.substr(start, i-start));\n \n// int cnt = 0, start = i+1;\n// for(; i<n; ++i)\n// if(!(cnt += (s[i]=='(' ? 1 : s[i]==')' ? -1 : 0))) break;\n// num = calculate(s.substr(start, i-start));\n// }else if(isdigit(c)) num = 10*num+c-'0';\n// if(c=='+' || c=='-' || c=='*' || c=='/' || i==n-1){ // NOTE: !!! No else before if\n// t = op=='+' ? t+num : op=='-' ? t-num : op=='*' ? t*num : (num ? t/num : INT_MAX);\n// if(c=='+' || c=='-' || i==n-1){\n// res += t;\n// t = 0;\n// }\n// num = 0;\n// op = c;\n// }\n// }\n// return res;\n// }\n \n \n\n \n \n \n // void eval(stack<int>& stk, const char& op, int val){\n // stk.push(op=='+' ? val : op=='-' ? -val : op=='*' ? stk.top()*val : (val ? stk.top()/val : INT_MAX));\n // }\n // // return <val, index>\n // pair<int,int> cal(const string& s){\n // char op = '+'; // lastOp\n // long num = 0;\n // stack<int> stk;\n // for(int i=0, n=s.size(); i<n; ++i){\n // char c = s[i];\n // if(isdigit(c)) num = 10*num+c-'0';\n // else if(c=='+' || c=='-' || c=='*' || c=='/'){\n // eval(stk, op, num);\n // op = c;\n // num = 0;\n // }else if(c=='('){\n // auto r = cal(s.substr(i+1));\n // num = r.first;\n // i += r.second;\n // }else if(c==')'){\n // eval(stk, op, num);\n // int sum = 0;\n // while(!stk.empty()) sum += stk.top(), stk.pop();\n // return {sum, i+1};\n // }\n // }\n // eval(stk, op, num);\n // int sum = 0;\n // while(!stk.empty()) sum += stk.top(), stk.pop();\n // return {sum, s.size()};\n // }\n // // Solution 2:\n // int calculate(const string& s) {\n // return cal(s).first;\n // }\n \n\n \n // unordered_map<char, int> m = {\n // {'(', 3},\n // {')', 3},\n // {'*', 2},\n // {'/', 2},\n // {'+', 1},\n // {'-', 1}\n // };\n // bool isLowerThan(const char& op1, const char& op2){\n // return m[op2]!=3 && m[op1]<=m[op2];\n // }\n // void handle(stack<int>& stk, stack<char>& op){\n // char c = op.top(); op.pop();\n // if(stk.size()==1){stk.top()*=(c=='-' ? -1 : 1); return;}\n // int second = stk.top(); stk.pop();\n // int first = stk.top(); stk.pop();\n // stk.push(c=='+' ? first+second : c=='-' ? first-second : c=='*' ? first*second : second ? first/second : INT_MAX);\n // }\n // int calculate(const string& s){\n // stack<int> stk;\n // stack<char> op;\n // for(int i=0, n=s.size(); i<n; ++i){\n // if(s[i]=='(') op.push('(');\n // else if(s[i]==')'){\n // while(op.top()!='(') handle(stk,op);\n // op.pop();\n // }else if(isdigit(s[i])){\n // long num = 0;\n // while(i<n && isdigit(s[i])) num=10*num+s[i++]-'0';\n // --i;\n // stk.push(num);\n // }else if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/'){\n // while(!op.empty() && isLowerThan(s[i], op.top())) handle(stk,op);\n // op.push(s[i]);\n // }\n // }\n // while(!op.empty()) handle(stk, op);\n // return stk.top();\n // }\n \n \n// unordered_map<char, int> m = { // can't handle 3-(-2)\n// {'(', 3},\n// {')', 3},\n// {'*', 2},\n// {'/', 2},\n// {'+', 1},\n// {'-', 1},\n// };\n// // op1<=op2\n// bool isLowerEqualThan(const char& op1, const char& op2){\n// return m[op2]!=3 && m[op1]<=m[op2];\n// }\n// void handle(stack<int>& stk, stack<char>& op){\n// const char c = op.top(); op.pop();\n// if(stk.size()==1) { // handle (-2)+1 or -2+1 // Can't handle 3-(-2)\n// stk.top()*=(c=='-' ? -1 : 1);\n// // cout << stk.top() << endl;\n// return;\n// }\n// int second = stk.top(); stk.pop();\n// int first = stk.top(); stk.pop();\n// stk.push(c=='+' ? first+second : c=='-' ? first-second : c=='*' ? first*second : !second ? INT_MAX : first/second);\n// }\n// int calculate(const string& s) { \n// stack<int> stk;\n// stack<char> op;\n// for(int i=0, n=s.size(); i<n; ++i){\n// if(s[i]=='(') op.push('(');\n// else if(s[i]==')'){\n// while(op.top()!='(') handle(stk, op);\n// op.pop();\n// }else if(isdigit(s[i])){\n// char c = op.top(); op.pop();\n \n// long num = 0, sign = \n// while(i<n && isdigit(s[i])) num = 10*num+s[i++]-'0';\n// --i;\n// char c = '\\0';\n// if(!op.empty() && op.top()=='-') c = op.top(), op.pop();\n// if(c=='-' && (!op.empty() && op.top()=='(')) stk.push(-num);\n// else op.push('-'), stk.push(num);\n// // stk.push(num);\n// }else if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/'){\n// while(!op.empty() && isLowerEqualThan(s[i],op.top())) handle(stk, op);\n// op.push(s[i]);\n// }\n// }\n// while(!op.empty()) handle(stk, op);\n// return stk.top();\n// }\n \n \n// /*\n// int res = 0, n = s.size(), num = 0;\n// vector<int> sign(2,1);\n// for(int i=0; i<n; ++i){\n// if(isdigit(s[i])){\n// while(i<n && isdigit(s[i])) num=10*num+s[i++]-'0';\n// res += num*sign.back();\n// sign.pop_back();\n// num = 0;\n// --i;\n// }else if(s[i] == ')') sign.pop_back();\n// else if(s[i] != ' ') sign.push_back(sign.back()*(s[i]=='-' ? -1 : 1));\n// }\n// return res;*/\n \n \n// /*int res = 0, n = s.size(), num = 0;\n// vector<int> sign (2, 1);\n// for(int i=0; i<n; ++i){\n// if(isdigit(s[i])){\n// num = 0;\n// while(i<n && isdigit(s[i])) num = num*10 + s[i++]-'0';\n// --i;\n// res += sign.back()* num;\n// sign.pop_back();\n// }else if(s[i] == ')') sign.pop_back();\n// else if(s[i] != ' ') sign.push_back(sign.back()*(s[i] == '-' ? -1 : 1));\n// }\n// return res;*/\n \n \n// /*int res = 0;\n// vector<int> signs(2,1);\n// for (int i=0; i<s.size(); ++i) {\n// char c = s[i];\n// if (isdigit(c)) { // same as: if (c >= '0') {\n// int number = 0;\n// while (i < s.size() && s[i] >= '0') number = 10 * number + s[i++] - '0';\n// --i;\n// res += signs.back() * number;\n// signs.pop_back();\n// } else if (c == ')') signs.pop_back();\n// else if (c != ' ') signs.push_back(signs.back() * (c == '-' ? -1 : 1));\n// }\n// return res;*/\n// }\n};",
"memory": "65618"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n int res = 0; \n int cur = 0; \n bool processing_num = false; \n bool is_neg = false; \n for (int i = 0; i < s.length(); i++) {\n char c = s[i]; \n\n if (c == '(') {\n int start = i; \n int len = 0; \n int cnt = 1; \n while (cnt != 0) {\n i++; \n len++;\n if (s[i] == ')')\n cnt--; \n if (s[i] == '(')\n cnt++;\n }\n int subexpr = calculate(s.substr(start + 1, len - 1)); \n res += is_neg ? -subexpr : subexpr; \n continue; \n }\n\n if ('0' <= c && c <= '9') {\n if (!processing_num)\n processing_num = true; \n cur = cur * 10 + (c - '0'); \n } else {\n if (processing_num)\n processing_num = false;\n\n if (cur > 0) {\n res += is_neg ? -cur : cur; \n cur = 0; \n }\n\n if (c == '-') {\n is_neg = true; \n continue; \n }\n\n if (c == ' ')\n continue; \n\n if (is_neg)\n is_neg = false; \n\n if (c == '+')\n continue; \n } \n\n if (i == s.length() - 1) \n res += is_neg ? -cur : cur; \n }\n return res;\n }\n};",
"memory": "66556"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int getNum(const string& s, int& i) {\n int num = 0;\n while (i < s.size() && isdigit(s[i])) {\n num = num * 10 + (s[i] - '0');\n i++;\n }\n i--;\n return num;\n }\n\n int calculate(string s) {\n char lastOp = 0;\n int lastNum = 0;\n int i = 0;\n\n while (i < s.size()) {\n if (isdigit(s[i])) {\n int num = getNum(s, i);\n\n if (lastOp == '+') {\n lastNum += num;\n } else if (lastOp == '-') {\n lastNum -= num;\n } else {\n lastNum = num;\n }\n } else if (s[i] == '+') {\n lastOp = '+';\n } else if (s[i] == '-') {\n lastOp = '-';\n } else if (s[i] == '(') {\n int counter = 1;\n int ind = i + 1;\n\n while (counter > 0) {\n if (s[ind] == '(')\n counter++;\n else if (s[ind] == ')')\n counter--;\n ind++;\n }\n\n int num = calculate(s.substr(i + 1, ind - i - 2));\n\n if (lastOp == '+') {\n lastNum += num;\n } else if (lastOp == '-') {\n lastNum -= num;\n } else {\n lastNum = num;\n }\n\n i = ind - 1;\n }\n i++;\n }\n\n return lastNum;\n }\n};",
"memory": "67493"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int getNum(const string& s, int& i) {\n int num = 0;\n while (i < s.size() && isdigit(s[i])) {\n num = num * 10 + (s[i] - '0');\n i++;\n }\n i--; \n return num;\n }\n\n int calculate(string s) {\n char lastOp = 0;\n int lastNum = 0;\n int i = 0;\n\n while (i < s.size()) {\n if (isdigit(s[i])) {\n int num = getNum(s, i);\n\n if (lastOp == '+') {\n lastNum += num;\n } else if (lastOp == '-') {\n lastNum -= num;\n } else {\n lastNum = num;\n }\n } else if (s[i] == '+') {\n lastOp = '+';\n } else if (s[i] == '-') {\n lastOp = '-';\n } else if (s[i] == '(') {\n int counter = 1;\n int ind = i + 1;\n\n while (counter > 0) {\n if (s[ind] == '(')\n counter++;\n else if (s[ind] == ')')\n counter--;\n ind++;\n }\n\n int num = calculate(s.substr(i + 1, ind - i - 2));\n\n if (lastOp == '+') {\n lastNum += num;\n } else if (lastOp == '-') {\n lastNum -= num;\n } else {\n lastNum = num;\n }\n\n i = ind - 1;\n }\n i++;\n }\n\n return lastNum;\n }\n};",
"memory": "68431"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\nprivate:\n string removeSpaces(string s){\n string result = \"\";\n for (int i = 0; i < s.length(); i++){\n if (s[i]!= ' ') {\n result+=s[i];\n }\n }\n return result;\n }\n vector<string> tokenize(string s){\n vector<string> result;\n string number = \"\";\n for (int i = 0; i < s.length(); i++){\n if (s[i] == '+' || s[i] == '-' || s[i] == '(' || s[i] == ')') {\n if (number != \"\") {\n result.push_back(number);\n }\n result.push_back(std::string{s[i]});\n number = \"\";\n } else {\n number += s[i];\n }\n }\n if (number != \"\") {\n result.push_back(number);\n }\n return result;\n }\n string evaluate(vector<string> operation) {\n int i = operation.size() - 1;\n // std::cout << \"Operation: [\";\n // for(string token: operation) {\n // std::cout << token << \",\";\n // }\n // std::cout << \"]\";\n while (operation.size() > 1) {\n if (operation[operation.size()- 1] == \"-\") {\n operation.pop_back();\n operation[operation.size() - 1] = std::to_string(-1 * std::stoi(operation[operation.size() - 1]));\n } else {\n string result = \"\";\n if (operation[operation.size() - 2 ] == \"+\") {\n result = std::to_string(std::stoi(operation[operation.size()-1]) + std::stoi(operation[operation.size()-3]));\n } else {\n result = std::to_string(std::stoi(operation[operation.size()-1]) - std::stoi(operation[operation.size()-3]));\n }\n operation[operation.size() - 3 ] = result;\n operation.pop_back();\n operation.pop_back();\n }\n }\n // std::cout << \" = \" << std::string{operation[0]} << std::endl;\n return std::string{operation[0]};\n }\npublic:\n int calculate(string s) {\n vector<string> tokens = tokenize(removeSpaces(s));\n if (tokens.size() == 1) {\n return std::stoi(tokens[0]);\n }\n stack<string> resolving;\n // std::cout << \"[\";\n // for(string token: tokens) {\n // std::cout << token << \",\";\n // }\n // std::cout << \"]\" << std::endl;\n resolving.push(tokens[0]);\n int i = 1;\n int finalResult = 0;\n while(resolving.size() > 0) {\n if (tokens[i] != \")\") {\n resolving.push(tokens[i]);\n } else {\n vector<string> operation;\n while (resolving.top() != \"(\") {\n operation.push_back(resolving.top());\n resolving.pop();\n }\n // std::reverse(operation.begin(), operation.end());\n resolving.pop();\n resolving.push(evaluate(operation));\n }\n i++;\n if (i == tokens.size()) {\n vector<string> operation;\n while (resolving.size() > 0) {\n operation.push_back(resolving.top());\n resolving.pop();\n }\n // std::reverse(operation.begin(), operation.end());\n finalResult = std::stoi(evaluate(operation));\n }\n }\n return finalResult;\n }\n};",
"memory": "69368"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n if (s.size() == 0)\n return 0;\n int tot = 0;\n int op = 0;\n int i = 0;\n while (i < s.size()) {\n int rhs = 0;\n while (s[i] == ' ') {\n i++;\n }\n\n if (s[i] == '+') {\n op = 1;\n i++;\n } else if (s[i] == '-') {\n op = -1;\n i++;\n }\n\n while (s[i] >= '0' && s[i] <= '9') {\n rhs *= 10;\n rhs += s[i] - '0';\n i++;\n }\n\n if (s[i] == '(') {\n int parens = 1;\n i++;\n int start = i;\n while (parens > 0) {\n switch (s[i]) {\n case '(':\n parens++;\n break;\n case ')':\n parens--;\n }\n i++;\n }\n\n rhs = calculate(s.substr(start, i - start - 1));\n }\n\n while (s[i] == ' ') {\n i++;\n }\n\n if (op == 0)\n tot = rhs;\n else\n tot += rhs * op;\n }\n\n return tot;\n }\n};",
"memory": "70306"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int getNum(const string& s, int& i) {\n int num = 0;\n while (i < s.size() && isdigit(s[i])) {\n num = num * 10 + (s[i] - '0');\n i++;\n }\n i--;\n return num;\n }\n\n int calculate(string s) {\n char lastOp = 0;\n int lastNum = 0;\n int i = 0;\n\n while (i < s.size()) {\n if (isdigit(s[i])) {\n int num = getNum(s, i);\n\n if (lastOp == '+') {\n lastNum += num;\n } else if (lastOp == '-') {\n lastNum -= num;\n } else {\n lastNum = num;\n }\n } else if (s[i] == '+') {\n lastOp = '+';\n } else if (s[i] == '-') {\n lastOp = '-';\n } else if (s[i] == '(') {\n int counter = 1;\n int ind = i + 1;\n\n while (counter > 0) {\n if (s[ind] == '(')\n counter++;\n else if (s[ind] == ')')\n counter--;\n ind++;\n }\n\n int num = calculate(s.substr(i + 1, ind - i - 2));\n\n if (lastOp == '+') {\n lastNum += num;\n } else if (lastOp == '-') {\n lastNum -= num;\n } else {\n lastNum = num;\n }\n\n i = ind - 1;\n }\n i++;\n }\n\n return lastNum;\n }\n};\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n return 0;\n}();",
"memory": "71243"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\nint calculate(string s) {\n std::vector<int> bidx;\n std::vector<int> sign = {1, 1};\n int n = s.length();\n int i = 0, res = 0;\n while (i < n) {\n if (s[i] >= '0' && s[i] <= '9') {\n int tmp = 0;\n while (s[i] >= '0' && s[i] <= '9') {\n tmp = tmp * 10 + (s[i] - '0');\n i++;\n }\n res += sign.back() * tmp;\n sign.pop_back();\n i--;\n } else if (s[i] == '+') {\n sign.push_back(sign.back());\n } else if (s[i] == '-') {\n sign.push_back(-sign.back());\n } else if (s[i] == ' ') {\n } else if (s[i] == '(') {\n int cnt = 1;\n int j = i;\n while (cnt > 0 && ++j < n) {\n if (s[j] == '(') {\n cnt++;\n } else if (s[j] == ')') {\n cnt--;\n }\n }\n res += sign.back() * calculate(s.substr(i + 1, j - i - 1));\n sign.pop_back();\n i = j;\n }\n i++;\n }\n\n return res;\n}\n};",
"memory": "72181"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int getNum(const string& s, int& i) {\n auto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n return 0;\n }();\n int num = 0;\n while (i < s.size() && isdigit(s[i])) {\n num = num * 10 + (s[i] - '0');\n i++;\n }\n i--;\n return num;\n }\n\n int calculate(string s) {\n char lastOp = 0;\n int lastNum = 0;\n int i = 0;\n\n while (i < s.size()) {\n if (isdigit(s[i])) {\n int num = getNum(s, i);\n\n if (lastOp == '+') {\n lastNum += num;\n } else if (lastOp == '-') {\n lastNum -= num;\n } else {\n lastNum = num;\n }\n } else if (s[i] == '+') {\n lastOp = '+';\n } else if (s[i] == '-') {\n lastOp = '-';\n } else if (s[i] == '(') {\n int counter = 1;\n int ind = i + 1;\n\n while (counter > 0) {\n if (s[ind] == '(')\n counter++;\n else if (s[ind] == ')')\n counter--;\n ind++;\n }\n\n int num = calculate(s.substr(i + 1, ind - i - 2));\n\n if (lastOp == '+') {\n lastNum += num;\n } else if (lastOp == '-') {\n lastNum -= num;\n } else {\n lastNum = num;\n }\n\n i = ind - 1;\n }\n i++;\n }\n\n return lastNum;\n }\n};",
"memory": "73118"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(const string& s) {\n int curRes = 0;\n\n int sign = 1;\n\n for (int i = 0; i < s.size(); i++) {\n if (s[i] == '(') {\n int startIndex = i + 1;\n int squareCount = 0;\n while (i < s.size()) {\n if (s[i] == '(') squareCount++;\n else if (s[i] == ')') squareCount--;\n\n if (squareCount == 0) {\n break;\n }\n i++;\n }\n\n curRes += sign * calculate(s.substr(startIndex, i - startIndex));\n }\n else if (isdigit(s[i])) {\n int startIndex = i;\n\n while (i < s.size() && isdigit(s[i + 1])) {\n ++i;\n }\n\n curRes += sign * stoi(s.substr(startIndex, i - startIndex + 1));\n }\n else if (s[i] == '+') {\n sign = 1;\n }\n else if (s[i] == '-') {\n sign = -1;\n }\n }\n\n return curRes;\n }\n};",
"memory": "74056"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n int sum = 0;\n return resolveExp(s);\n }\n int resolveExp(string s)\n {\n int operand1 = 0;\n int operand2 = 0;\n int pos = 0;\n bool waiting = false;\n int op = 0; // -1 if subtraction, 1 if addition\n int result = 0;\n while (pos < s.length())\n {\n if (s[pos] == ' ')\n {\n pos++;\n continue;\n }\n else if (s[pos] == '(')\n {\n int last = pos + 1;\n int numOpen = 1;\n int numClose = 0;\n while (numOpen != numClose)\n {\n if (s[last] == '(')\n {\n numOpen++;\n }\n else if (s[last] == ')')\n {\n numClose++;\n }\n last++;\n }\n if (waiting)\n {\n operand2 = resolveExp(s.substr(pos + 1, last - pos));\n if (op == 1)\n {\n result = operand1 + operand2;\n operand1 = result;\n }\n else if (op == -1)\n {\n result = operand1 - operand2;\n operand1 = result;\n }\n waiting = false;\n }\n else\n {\n printf(\"substr: %s\\n\", s.substr(pos + 1, last - pos).c_str());\n operand1 = resolveExp(s.substr(pos + 1, last - pos));\n printf(\"%d\\n\", operand1);\n waiting = true;\n }\n pos = last;\n }\n else if (s[pos] == '+')\n {\n op = 1;\n waiting = true;\n pos++;\n }\n else if (s[pos] == '-')\n {\n op = -1;\n waiting = true;\n pos++;\n }\n else if (s[pos] == ')')\n {\n if (waiting)\n {\n result = operand1;\n }\n return result;\n }\n else\n {\n int last = pos + 1;\n while (isdigit(s[last]))\n {\n last++;\n }\n string digit = s.substr(pos, last - pos);\n if (waiting)\n {\n operand2 = atoi(digit.c_str());\n if (op == 1)\n {\n result = operand1 + operand2;\n operand1 = result;\n }\n else if (op == -1)\n {\n result = operand1 - operand2;\n operand1 = result;\n }\n waiting = false;\n }\n else\n {\n operand1 = atoi(digit.c_str());\n waiting = true;\n }\n pos = last;\n }\n }\n if (waiting)\n {\n result += operand1;\n }\n return result;\n }\n};",
"memory": "74993"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n/*\nexpr := 0 | [1-9][0-9]*\nexpr := (expr)\nexpr := expr + expr\nexpr := expr - expr\n*/\n int calculate(string s) {\n int acc = 0;\n char op = '+';\n\n for(int i = 0; i < s.size(); ++i) {\n if(s[i] == ' ') continue; // whitespace\n else if(isdigit(s[i])) { // number\n int len = 1;\n while(i+len < s.size()) {\n if(!isdigit(s[i+len])) break;\n len++;\n }\n int n = stoi(s.substr(i,len));\n acc += (op == '+' ? n : -n);\n i += len-1;\n }\n else if(s[i] == '+' || s[i] == '-') { \n op = s[i];\n }\n else if(s[i] == '(') {\n int bcount = 1;\n int len = 0;\n while(bcount != 0 && i+len < s.size()) {\n ++len;\n if(s[i+len] == ')') --bcount;\n else if(s[i+len] == '(') ++bcount;\n }\n\n int n = calculate(s.substr(i+1, len-1));\n \n acc += (op == '+' ? n : -n);\n i += len;\n }\n }\n \n return acc;\n }\n};",
"memory": "75931"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n int calculate(string s) {\n int res=0;\n int sign = 1;\n for(int i=0; i<s.length(); ++i)\n {\n if(s[i] == ' ') continue;\n if(s[i] == '+' || s[i] == '-')\n {\n sign = s[i] =='+' ? 1:-1;\n continue;\n } \n\n if(s[i] == '(')\n {\n int start = i, open=1; ++i;\n while(open >0)\n {\n if(s[i] == '(') ++open;\n else if(s[i] == ')') --open;\n ++i;\n }\n res += sign*calculate(s.substr(start+1,i-start-2)); \n }\n else\n {\n int start = i;\n while(i<s.length() && s[i]-'0'>=0 && s[i]-'9' <=9) ++i;\n res += sign*stoi(s.substr(start,i-start)); \n }\n --i;\n }\n return res;\n }\n};",
"memory": "76868"
} |
224 | <p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1 + 1"
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " 2-1 + 2 "
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
<li><code>s</code> represents a valid expression.</li>
<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
<li>There will be no two consecutive operators in the input.</li>
<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
| 3 | {
"code": "class Solution {\npublic:\n string solve(vector<string>v){\n stack<string>st;\n for(int i=0;i<v.size();i++){\n if(v[i] == \"-\"){\n int x = 0;\n if(st.empty() == false){\n x = stoi(st.top());\n st.pop();\n }\n int y = stoi(v[i+1]);\n st.push(to_string(x-y));\n i++;\n }else if(v[i] ==\"+\"){\n int x = 0;\n if(st.empty() == false){\n x = stoi(st.top());\n st.pop();\n }\n int y = stoi(v[i+1]);\n st.push(to_string(x+y));\n i++;\n }else{\n st.push(v[i]);\n }\n }\n return st.top();\n }\n int calculate(string s) {\n vector<string>nums;\n string temp;\n//--------------------------------------------------//\n/*\n removed unnecessary spaces and converted each element to \n string and stored in a vector.\n*/\n for(int i=0;i<s.size();i++){\n if(s[i] == ' '){\n continue;\n }\n if(isdigit(s[i])){\n temp += s[i];\n }else{\n if(temp.empty() == false){\n nums.push_back(temp);\n }\n string t;\n t += s[i];\n nums.push_back(t);\n temp.clear();\n }\n }\n if(temp.empty() == false){\n nums.push_back(temp);\n }\n//--------------------------------------------------//\n stack<string>st;\n for(int i=0;i<nums.size();i++){\n vector<string>t;\n if(nums[i] == \")\"){\n while(st.empty() == false && st.top() != \"(\"){\n t.push_back(st.top());\n st.pop();\n }\n st.pop();\n reverse(t.begin(),t.end());\n string ans = solve(t);\n st.push(ans);\n }else{\n st.push(nums[i]);\n }\n }\n vector<string>v1;\n while(st.empty() == false){\n v1.push_back(st.top());\n st.pop();\n }\n reverse(v1.begin(),v1.end());\n return stoi(solve(v1));\n }\n};",
"memory": "77806"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.