Question

Please help with this. The hint refers to the attached picture.

Read Section 6.1.5 (p.235) on the Parenthesis Matching problem. They gave 5 examples: the first two are correct, and the r1/** Tests if delimiters in the given expression are properly matched./ 2 public static boolean isMatched(String expression)

Read Section 6.1.5 (p.235) on the Parenthesis Matching problem. They gave 5 examples: the first two are " correct", and the remaining 3 "incorrect". Notice that the last one is actually "fixable". You just have to append the string")" to the input to get a properly matched expression! Here is another example: the string (O[(is incorrect, but is fixable if you append )]) Thus we want to classify the input expressions into " fixable" and" unfixable" When fixable, we want to return a string that can be appended to the input to be "correct". In particular, if a "correct" input is "fixable" (you just append the empty string). Write a method with this header: String isMatched(String expression); It should be similar to the code fragment 6.7 in page 236, except that we return a String. When the input expression is " unfixable", we return the string "X". If it is "fixable", return the string to fix the input string. HINT: you can reuse most of the code in page 236.
1/** Tests if delimiters in the given expression are properly matched./ 2 public static boolean isMatched(String expression) { 3 final String opening ' opening delimiters /respective closing delimiters 4 final String closing Stack-Character> buffer-new LinkedStack(); 6 for (char c : expression.toCharArray)) { if (opening. indexOf(c)--1) this is a left delimiter buffer.push(c); 9 else if (closing.indexOf(c) !--1){this is a right delimiter 10 if (buffer.isEmpty()) /nothing to match with return false; if (closing.indexOf(c) opening.indexOf (buffer.pop())) 12 13 14 15 16 return buffer.isEmpty); 17 return false; //mismatched delimiter // were all opening delimiters matched?
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

public static String isMatched(String expression) {

      final String opening = "({[";

      final String closing = ")}]";

      Stack<Character> buffer = new LinkedStack<Character>();

      for (char c : expression.toCharArray()) {

            if (opening.indexOf(c) != -1) {

                  buffer.push(c);

            } else if (closing.indexOf(c) != -1) {

                  if (buffer.isEmpty()) {

                        // unfixable

                        return "X";

                  }

                  if (closing.indexOf(c) != opening.indexOf(buffer.pop())) {

                        // unfixable

                        return "X";

                  }

            }

      }

      // fixable

      String appendable = "";

      // appending remaining closing characters corresponding to elemenets in

      // stack to a String variable that can be appended to expression to make

      // the expression fixable, if not.

      while (!buffer.isEmpty()) {

            // popping a char from buffer

            char c = buffer.pop();

            // finding index of c in opening

            int index = opening.indexOf(c);

            // appending corresponding closing bracket to string

            appendable += closing.charAt(index);

      }

      return appendable;

}

Add a comment
Know the answer?
Add Answer to:
Read Section 6.1.5 (p.235) on the Parenthesis Matching problem. They gave 5 examples: the first t...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Let’s build a dynamic string tokenizer! Start with the existing template and work on the areas...

    Let’s build a dynamic string tokenizer! Start with the existing template and work on the areas marked with TODO in the comments: Homework 8 Template.c Note: If you turn the template back into me without adding any original work you will receive a 0. By itself the template does nothing. You need to fill in the code to dynamically allocate an array of strings that are returned to the user. Remember: A string is an array. A tokenizer goes through...

  • Problem 5-18 Journal Entries; T-Accounts; Cost Flows [LO4, LO5, LO7] Ravsten Company uses a job-order costing system. On...

    Problem 5-18 Journal Entries; T-Accounts; Cost Flows [LO4, LO5, LO7] Ravsten Company uses a job-order costing system. On January 1, the beginning of the current year, the company’s inventory balances were as follows:      Raw materials $ 20,000   Work in process $ 11,600   Finished goods $ 30,800 The company applies overhead cost to jobs on the basis of machine-hours. For the current year, the company estimated that it would work 36,800 machine-hours and incur $171,120 in manufacturing overhead cost. The following...

  • For this assignment, suppose that a fence is recording entry and exit into the park via...

    For this assignment, suppose that a fence is recording entry and exit into the park via a string as the gate swings open and folks walk in or out with their pet. For example, C++ DP+dp+CP+cp would indicate that an adult dog and an adult entered the park, then a puppy and child entered the park, then an adult cat and an adult entered the park and finally a kitten and a child entered the park. From this information, note...

  • !!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random...

    !!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random text with my generateText method, you can move on to the second step. Create a third class called Generator within the cs1410 package. Make class. This class should have a main method that provides a user interface for random text generation. Your interface should work as follows: Main should bring up an input dialog with which the user can enter the desired analysis level...

  • **TStack.py below** # CMPT 145: Linear ADTs # Defines the Stack ADT # # A stack (also called a pushdown or LIFO stack)...

    **TStack.py below** # CMPT 145: Linear ADTs # Defines the Stack ADT # # A stack (also called a pushdown or LIFO stack) is a compound # data structure in which the data values are ordered according # to the LIFO (last-in first-out) protocol. # # Implementation: # This implementation was designed to point out when ADT operations are # used incorrectly. def create(): """ Purpose creates an empty stack Return an empty stack """ return '__Stack__',list() def is_empty(stack): """...

  • Need help doing program In bold is problem E2 #include<iostream> #include<string> #include<vector> using namespace std; //Car...

    Need help doing program In bold is problem E2 #include<iostream> #include<string> #include<vector> using namespace std; //Car class //Defined enum here enum Kind{business,maintenance,other,box,tank,flat,otherFreight,chair,seater,otherPassenger}; //Defined array of strings string KIND_ARRAY[]={"business","maintenance","other,box","tank,flat","otherFreight","chair","seater","otherPassenger"}; class Car { private: string reportingMark; int carNumber; Kind kind; //changed to Kind bool loaded; string destination; public: //Defined setKind function Kind setKind(string knd) { for(int i=0;i<8;i++) //repeat upto 8 kinds { if(knd.compare(KIND_ARRAY[i])==0) //if matched in Array kind=(Kind)i; //setup that kind } return kind; } //Default constructor Car() { } //Parameterized constructor...

  • The last 3 cases are tests .cpp files to test the code. The language of this...

    The last 3 cases are tests .cpp files to test the code. The language of this code must be C++ because that is the only I am familiar with. Soreland, a software company, is planning on releasing its first C++ compiler with the hopes of putting MiniSoft's Visual C++ out of business (that reminds me of another story). Consequently, Soreland has contracted with the Fruugle Corporation to design and build part of their compiler. Of course, since Fruugle gets all...

  • Don't attempt if you can't attempt fully, i will dislike a nd negative comments would be...

    Don't attempt if you can't attempt fully, i will dislike a nd negative comments would be given Please it's a request. c++ We will read a CSV files of a data dump from the GoodReads 2 web site that contains information about user-rated books (e.g., book tit le, publication year, ISBN number, average reader rating, and cover image URL). The information will be stored and some simple statistics will be calculated. Additionally, for extra credit, the program will create an...

  • Don't attempt if you can't attempt fully, i will dislike and negative comments would be given...

    Don't attempt if you can't attempt fully, i will dislike and negative comments would be given Please it's a request. c++ We will read a CSV files of a data dump from the GoodReads 2 web site that contains information about user-rated books (e.g., book titnle, publication year, ISBN number, average reader rating, and cover image URL). The information will be stored and some simple statistics will be calculated. Additionally, for extra credit, the program will create an HTML web...

  • Activity: Writing Classes Page 1 of 10 Terminology attribute / state behavior class method header class...

    Activity: Writing Classes Page 1 of 10 Terminology attribute / state behavior class method header class header instance variable UML class diagram encapsulation client visibility (or access) modifier accessor method mutator method calling method method declaration method invocation return statement parameters constructor Goals By the end of this activity you should be able to do the following: > Create a class with methods that accept parameters and return a value Understand the constructor and the toString method of a class...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT