<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>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;1 + 1&quot;
<strong>Output:</strong> 2
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot; 2-1 + 2 &quot;
<strong>Output:</strong> 3
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot;
<strong>Output:</strong> 23
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>
	<li><code>s</code> consists of digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li>
	<li><code>s</code> represents a valid expression.</li>
	<li><code>&#39;+&#39;</code> is <strong>not</strong> used as a unary operation (i.e., <code>&quot;+1&quot;</code> and <code>&quot;+(2 + 3)&quot;</code> is invalid).</li>
	<li><code>&#39;-&#39;</code> could be used as a unary operation (i.e., <code>&quot;-1&quot;</code> and <code>&quot;-(2 + 3)&quot;</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>

def tokenize(s: str) -> List[Union[str, int]]:
    tokens = []

    for c in s:
        if c.isdigit():
            if not tokens or not isinstance(tokens[-1], int):
                tokens.append(0)
            tokens[-1] = 10 * tokens[-1] + int(c)
        elif c != ' ':
            tokens.append(c)
    
    return tokens

def map_parentheses(tokens: List[Union[str, int]]) -> Dict[int, int]:
    stack = []
    mapping = {}
    for i, token in enumerate(tokens):
        if token == '(':
            stack.append(i)
        elif token == ')':
            mapping[i] = (j := stack.pop())
            mapping[j] = i
    return mapping

def find_operator(tokens: List[Union[str, int]], mapping: Dict[int, int], L: int, R: int) -> int:
    i = L
    j = None

    while i <= R:
        if i in mapping:
            i = mapping[i] + 1
            continue
        if tokens[i] is int:
            continue
        if tokens[i] == '+':
            return i
        if tokens[i] == '-' and i > L:
            return i
        if tokens[i] == '*':
            j = i
        i += 1
    
    assert j is not None
    return j

def solve(tokens: List[Union[str, int]], mapping: Dict[int, int], L: int, R: int) -> int:
    if L > R:
        raise RuntimeError()
    if L in mapping and mapping[L] == R:
        return solve(tokens, mapping, L + 1, R - 1)
    if L == R:
        assert isinstance(tokens[L], int)
        return tokens[L]
    if L == R - 1 and tokens[L] == '-' and isinstance(tokens[R], int):
        return -tokens[R]
    if tokens[L] == '-' and (L + 1) in mapping and mapping[L + 1] == R:
        return -solve(tokens, mapping, L + 2, R - 1)
    
    i = find_operator(tokens, mapping, L, R)

    if tokens[i] == '+':
        return solve(tokens, mapping, L, i - 1) + solve(tokens, mapping, i + 1, R)
    if tokens[i] == '-':
        return solve(tokens, mapping, L, i - 1) + solve(tokens, mapping, i, R)
    if tokens[i] == '*':
        return solve(tokens, mapping, L, i - 1) * solve(tokens, mapping, i + 1, R)
    raise RuntimeError()

class Solution:
    def calculate(self, s: str) -> int:
        tokens = tokenize(s)
        mapping = map_parentheses(tokens)
        return solve(tokens, mapping, 0, len(tokens) - 1)

27145