Question: C++ code Create a function is_valid, which takes three strings, expr, left, and right, and returns true if expr represents a valid expression as regards

C++ code

Create a function is_valid, which takes three strings, expr, left, and right, and returns true if expr represents a valid expression as regards the proper nesting of the left and right delimiters contained in left and right. Here the delimiters are all single characters, so each index in left and rightcorresponds to one delimiter pair.

Notes and Constraints

expr contains between 0 and 50 characters, inclusive.

Each character in left represents the left delimiter of a pair, and the corresponding character in right is the associated right delimiter.

left and right contain between 0 and 5 characters, inclusive, and contain the same number of characters.

left contains none of the same characters as right, and there are no duplicates in either string.

Characters other than the delimiters are irrelevant to the problem and can be ignored.

Examples

"(easy)" "(" ")" return true 
 "({oops)}" "({" ")}" return false 

Improper nesting - the context opened by the left parenthesis closes before the inner context opened by the left curly brace.

My code (things in bold CANNOT be changed and all work must be done within the bolded code):

bool is_valid(string expr, string left, string right) { // fill in this method (and others you can write) int left_brack = 0; int left_paren = 0; int left_square = 0; int right_brack = 0; int right_paren = 0; int right_square = 0; int paren = 0; int pole = 0; int carrot = 0; string total = left + expr + right; bool match = true; bool messy = false; for(int i = 0; i < total.size(); i++){ char temp = total[i]; switch(temp){ case ')': right_paren++; break; case '}': right_brack++; break; case ']': right_square++; break; case '(': left_paren++; break; case '{': left_brack++; break; case '[': left_square++; break; case '|': pole++; break; case '"': paren++; break; case '^': carrot++; break; } if (i >=1){ if(total[i] = ']' && total[i-1] == ')'){ messy = true; } } } if (left_brack != right_brack) match = false; if (left_paren != right_paren) match = false; if (left_square != right_square) match = false; if (pole % 2 != 0) match = false; if (carrot == 1) match = false; if (messy) match = true; return match;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!