LeetCode Solutions

439. Ternary Expression Parser

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  string parseTernary(string expression) {
    const char c = expression[i];

    if (i + 1 == expression.length() || expression[i + 1] == ':') {
      i += 2;  // Skip ':'
      return string(1, c);
    }

    i += 2;  // Skip '?'
    const string& first = parseTernary(expression);
    const string& second = parseTernary(expression);
    return c == 'T' ? first : second;
  }

 private:
  int i = 0;
};
			

class Solution {
  public String parseTernary(String expression) {
    final char c = expression.charAt(i);

    if (i + 1 == expression.length() || expression.charAt(i + 1) == ':') {
      i += 2; // Skip ':'
      return String.valueOf(c);
    }

    i += 2; // Skip '?'
    final String first = parseTernary(expression);
    final String second = parseTernary(expression);
    return c == 'T' ? first : second;
  }

  private int i = 0;
}
			

class Solution:
  def parseTernary(self, expression: str) -> str:
    c = expression[self.i]

    if self.i + 1 == len(expression) or expression[self.i + 1] == ':':
      self.i += 2
      return str(c)

    self.i += 2
    first = self.parseTernary(expression)
    second = self.parseTernary(expression)

    return first if c == 'T' else second

  i = 0