Skip to content

439. Ternary Expression Parser 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  string parseTernary(string expression) {
    const char c = expression[i];

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

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

 private:
  int i = 0;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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 ':'s.
      return String.valueOf(c);
    }

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

  private int i = 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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