My DFS version

class Solution { public String parseTernary(String expression) { if (expression == null || expression.length() == 0) { return ""; } return dfs(expression, 0, expression.length() - 1); } public String dfs(String expression, int start, int end) { if (start == end) { return String.valueOf(expression.charAt(start)); } int count = 1; int i = start + 2; for (; i <= end; i++) { if (expression.charAt(i) == '?') { count++; } else if (expression.charAt(i) == ':'){ count--; } if (count == 0) { break; } } if (expression.charAt(start) == 'T') { return dfs(expression, start + 2, i - 1); } return dfs(expression, i + 1, end); } }Ternary Expression Parser