Leetcode

Ternary Expression Parser

  • Time:O(n)
  • Space:O(n)

C++

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

JAVA

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

Python

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