The Score of Students Solving Math Expression — LeetCode 2019 Python Solution
- Problem
- #2019
- Pattern
- Stack
- Reading time
- 6 min
- Source
- leetcode.com
The problem
You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students.
Example
- Input
- s = "7+3*1*2", answers = [20,13,42]
- Output
- 7
- Explanation
- As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]
Python solution
class Solution:
def scoreOfStudents(self, s: str, answers: List[int]) -> int:
def cal(s: str) -> int:
res, pre = 0, int(s[0])
for i in range(1, n, 2):
if s[i] == "*":
pre *= int(s[i + 1])
else:
res += pre
pre = int(s[i + 1])
res += pre
return res
n = len(s)
x = cal(s)
m = (n + 1) >> 1
f = [[set() for _ in range(m)] for _ in range(m)]
for i in range(m):
f[i][i] = {int(s[i << 1])}
for i in range(m - 1, -1, -1):
for j in range(i, m):
for k in range(i, j):
for l in f[i][k]:
for r in f[k + 1][j]:
if s[k << 1 | 1] == "+" and l + r <= 1000:
f[i][j].add(l + r)
elif s[k << 1 | 1] == "*" and l * r <= 1000:
f[i][j].add(l * r)
cnt = Counter(answers)
ans = cnt[x] * 5
for k, v in cnt.items():
if k != x and k in f[0][m - 1]:
ans += v << 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^3 \times M^2) |
| Space | O(n^2 \times M^2) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2019. The Score of Students Solving Math Expression is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2019. The Score of Students Solving Math Expression?
- LeetCode 2019. The Score of Students Solving Math Expression is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2019. The Score of Students Solving Math Expression?
- The Python solution on this page runs in O(n^3 \times M^2).
- What is the space complexity of LeetCode 2019. The Score of Students Solving Math Expression?
- The Python solution on this page uses O(n^2 \times M^2) auxiliary space.
- What topics does LeetCode 2019. The Score of Students Solving Math Expression cover?
- LeetCode 2019. The Score of Students Solving Math Expression is tagged Stack, Memoization, Array, Hash Table, Math, String and Dynamic Programming on LeetCode.