C#, DFS, easy to understand


  • 0
    A
    public class Solution
    {
        public string ParseTernary(string expression) 
        {
            int expLen;
            return helper(expression.ToCharArray(), 0, out expLen);
        }
        
        private string helper(char[] exp, int start, out int expLen)
        {
            expLen = 1;
            if(start == exp.Length - 1 || exp[start + 1] == ':')
            {
                return exp[start].ToString();
            }
            else
            {
                expLen++; // for "?"   
                
                int trueExpLen = 0, falseExpLen = 0;
                
                string trueBranchVal = helper(exp, start + 2, out trueExpLen);
                expLen += trueExpLen + 1; // for ":"
                
                string falseBranchVal = helper(exp, start + expLen, out falseExpLen);
                expLen += falseExpLen;
            
                if(exp[start] == 'T') return trueBranchVal;
                else return falseBranchVal;
            }        
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.