<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>

from dataclasses import dataclass

@dataclass
class Expression:
  def evaluate(self):
    raise NotImplementedError()

  # @classmethod
  # def list_from_tokens(cls, tokens: List[str]) -> Tuple["Expression", List[str]]:
  #   assert len(tokens) > 0
  #   if tokens[0] == "-":
  #     sub_expression, leftover_tokens = Expression.from_tokens(tokens[1:])
  #     return Negation(sub_expression), leftover_tokens
  #   elif tokens[0] == "(":
  #     end_paren = len(tokens) - 1
  #     while tokens[end_paren] != ")":
  #       end_paren -= 1
  #     return Sum()

  @classmethod
  def from_tokens(
    cls,
    tokens: List[str],
    first: int,
    last: int,
  ) -> List["Expression"]:
    if first == last:
      return []

    if isinstance(tokens[first], int):
      return [Number(value=tokens[first])] + Expression.from_tokens(tokens, first + 1, last)
    elif tokens[first] == "-":
      remaining_expressions = Expression.from_tokens(tokens, first + 1, last)
      remaining_expressions[0] = Negation(remaining_expressions[0])
      return remaining_expressions
    elif tokens[first] == "(":
      stack_depth = 0
      for end_paren_pos in range(first, last + 1):
        if tokens[end_paren_pos] == "(":
          stack_depth += 1
        elif tokens[end_paren_pos] == ")":
          stack_depth -= 1
        if stack_depth == 0:
          break
      expressions_from_remaining = Expression.from_tokens(tokens, end_paren_pos+1, last)
      paren_part = Sum(sub_expressions=Expression.from_tokens(
        tokens,
        first + 1,
        end_paren_pos
      ))
      return [paren_part] + expressions_from_remaining
    raise ValueError(f"How did my list of tokens become {tokens}?")
          

@dataclass
class Number(Expression):
  value: int
  def evaluate(self):
    return self.value
  def __repr__(self):
    return str(self.value)

@dataclass
class Sum(Expression):
  sub_expressions: List["Expression"]
  def evaluate(self):
    return sum(sub_expression.evaluate() for sub_expression in self.sub_expressions)
  def __repr__(self):
    return "(" + " + ".join(str(sub_expression) for sub_expression in self.sub_expressions) + ")"


@dataclass
class Negation(Expression):
  sub_expression: "Expression"
  def evaluate(self):
    return -self.sub_expression.evaluate()

  def __repr__(self):
    return "-" + str(self.sub_expression)


class Solution:
    def calculate(self, s: str) -> int:
      tokens = []
      digits = set("0123456789")
      other = set("()-")
      for i, c in enumerate(s):
        if c in digits:
          if i == 0 or s[i-1] not in digits:
            tokens.append(0)
          tokens[-1] = tokens[-1] * 10 + int(c)
        elif c in other:
          tokens.append(c)
      if len(tokens) == 0:
        return 0
      tokens = ["("] + tokens + [")"]
      expression = Expression.from_tokens(tokens, 0, len(tokens))
      return expression[0].evaluate()
        
40978