Given a string representing arbitrarily nested ternary expressions, calculate the result of the expression. Can always assume this given expression is valid and only consists of digits 0-9,?,:, T and F (T and F represent True and False respectively). Note:the length of the given string is≤10000. Each number would contain only one digit. The conditional Expressions group Right-to-Left (as usual in the most languages). The condition is always being either T or F. That's, the condition would never be a digit. The result of the expression would always evaluate to either a digit0-9, T or F.example1: Input:"T?2:3"Output:"2"explanation:iftrue, then result is 2; Otherwise result is 3. Example2: Input:"F?1:t?4:5"Output:"4"explanation:the Conditional Expressions Group Right-to-left. Using parenthesis, it is read/evaluated as:"(F? 1: (T? 4:5)) "" (F? 1: (T? 4:5)) "-" (F? 1:4) "or" (T? 4:5) "4", "4"Example3: Input:T? T? F:5:3 "Output:Fexplanation:the Conditional Expressions Group Right-to-left. Using parenthesis, it is read/evaluated as:"(T?) T? F:5): 3) "" (T? T? F:5): 3) "--" (T? F:3) "Or--" (T? F:5) "F", "F"
My First Solution:
Use Stack and String operation, from the back of the String, find the first '? ', push the right to Stack. Depends on whether the char before '? ' was ' T ' or ' F ', keep the corresponding string in the stack
1 Public classSolution {2 Publicstring Parseternary (string expression) {3Stack<string> st =NewStack<string>();4 intpos = Expression.lastindexof ("?"));5 while(Pos > 0) {6 if(Pos < Expression.length ()-1) {7String str = expression.substring (pos+1);8string[] STRs = Str.split (":");9 for(intI=strs.length-1; i>=0; i--) {Ten if(Strs[i].length () > 0) One St.push (Strs[i]); A } - } -String POP1 =St.pop (); theString POP2 =St.pop (); - if(Expression.charat (pos-1) = = ' T ') St.push (POP1); - ElseSt.push (POP2); -expression = expression.substring (0, Pos-1); +pos = Expression.lastindexof ("?")); - } + returnSt.pop (); A } at}
Better solution, refer to https://discuss.leetcode.com/topic/64409/ Very-easy-1-pass-stack-solution-in-java-no-string-concat/2
No String contat/substring operation
1 Publicstring Parseternary (string expression) {2 if(Expression = =NULL|| Expression.length () = = 0)return"";3deque<character> stack =NewLinkedlist<>();4 5 for(inti = Expression.length ()-1; I >= 0; i--) {6 Charc =Expression.charat (i);7 if(!stack.isempty () && stack.peek () = = '? ') {8 9Stack.pop ();//pop '? 'Ten CharFirst =Stack.pop (); OneStack.pop ();//Pop ': ' A CharSecond =Stack.pop (); - - if(c = = ' T ') Stack.push (first); the ElseStack.push (second); -}Else { - Stack.push (c); - } + } - + returnstring.valueof (Stack.peek ()); A}
Leetcode:ternary Expression Parser