C++ recursive solution


  • 0
    G
    class Solution {
    public:
        string parseTernary(string expression) 
        {
            if(expression.empty())
            {
                return "";
            }
            
            if(expression[0] == '(')
            {
                return parseTernary(expression.substr(1,expression.size() - 2));
            }
            
            if(expression.find("?") == std::string::npos)
            {
                return (expression);
            }
            
            int start = 1;
            int Count = 0;
            
            for(;start < expression.size();start++)
            {
                if(expression[start] == '?')
                {
                    Count++;
                }
                else if(expression[start] == ':')
                {
                    Count--;
                    
                    if(Count == 0)
                    {
                        break;
                    }
                }
            }
            
            if(expression[0] == 'T')
            {
                return parseTernary(expression.substr(2,start - 2));
            }
           
            return parseTernary(expression.substr(start + 1));
        }
    };

Log in to reply
 

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