[Leetcode] Ternary expression Parser Three-dimensional expressions parser

Source: Internet
Author: User

Given a string representing arbitrarily nested ternary expressions, calculate the result of the expression. You can always assume this given expression is valid and only consists 0-9 of digits,, ? : , and T F ( T and F represent True and False respectively).

Note:

    1. The length of the given string is≤10000.
    2. Each number would contain only one digit.
    3. The Conditional Expressions group Right-to-left (as usual in most languages).
    4. The condition is always either T or F . That's, the condition would never be a digit.
    5. The result of the expression would always be evaluate to either a digit 0-9 , T or F .

Example 1:

Input: "T?2:3" Output: "2" explanation:if true, then result is 2; Otherwise result is 3.

Example 2:

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"

Example 3:

Input: "T?" T? F:5:3 "Output:" F "explanation: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"                                    

This problem lets us parse a ternary expression, we can know by analyzing the example of the problem, if there are more than one ternary expression nested, then we would like to start from the right to find the first question mark, and then process the ternary expression, and then step-by-step to the left, This also conforms to the feature that the program is executed from right to left. So the first thing I think of is to use a stack to record all the question mark position, and then according to the position of this question mark, take out the current ternary expression, call an eval function to parse the results, can do this because the topic is limited to three-dimensional expression of each part only one character, And the ternary expression that needs to be analyzed is legal, then we stitch the results of the analysis and the two segments into a new string, continue to deal with the previous question mark, so that when all the question mark processing is complete, the remaining character is the answer, see the code is as follows:

Solution One:

classSolution { Public:    stringParseternary (stringexpression) {        stringres =expression; Stack<int>s;  for(inti =0; I < expression.size (); ++i) {if(Expression[i] = ='?') S.push (i); }         while(!S.empty ()) {            intt =s.top (); S.pop (); Res= Res.substr (0, T-1) + eval (res.substr (T-1,5) + RES.SUBSTR (t +4); }        returnRes; }    stringEvalstringstr) {        if(Str.size ()! =5)return ""; returnstr[0] =='T'? STR.SUBSTR (2,1): Str.substr (4); }};

The following method is also the use of stack stack idea, but the difference is not the location of the question mark, but the existence of all the characters, the original array from the back and forward, the traversal of the characters are pressed into the stack, we detect if the stack is the first element is a question mark, indicating that we are currently traversing to the character is T or F, Then remove the first part, then remove the colon, and then take out the second part, we judge according to the current character which part into the stack, so that after the completion of the traversal, all the question marks are processed, the remaining stack top element is the request:

Solution Two:

classSolution { Public:    stringParseternary (stringexpression) {Stack<Char>s;  for(inti = expression.size ()-1; I >=0; --i) {Charc =Expression[i]; if(!s.empty () && s.top () = ='?') {s.pop (); CharFirst =s.top (); S.pop ();                S.pop (); CharSecond =s.top (); S.pop (); S.push (c=='T'?First:second); } Else{s.push (c); }        }        return string(1, S.top ()); }};

The following method is more concise, no use of the stack, but the use of the STL built-in function find_last_of, used to find the string in the last position of the current string, here we find the last question mark appears in the position, just the right question mark, we do with the solution of a similar processing, Stitching strings, looping, see the code below:

Solution Three:

classSolution { Public:    stringParseternary (stringexpression) {        stringres =expression;  while(Res.size () >1) {            inti = res.find_last_of ("?"); Res= Res.substr (0I1) +string(1, Res[i-1] =='T'? Res[i +1]: Res[i +3]) + RES.SUBSTR (i +4); }        returnRes; }};

Resources:

Https://discuss.leetcode.com/topic/64389/easy-and-concise-5-lines-python-java-solution

Https://discuss.leetcode.com/topic/64409/very-easy-1-pass-stack-solution-in-java-no-string-concat/2

Leetcode all in one topic summary (continuous update ...)

[Leetcode] Ternary expression Parser Three-dimensional expressions parser

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.