Programming challenge description: Given a string comprising just of the characters (,),{,},[,] determine if it is well-formed or not. Input: Your program should read lines from standard input. Each line contains a string comprising of the characters mentioned above. There is no whitespace between characters. Output: Print out True if the string is well-formed, False otherwise.

Respuesta :

Answer:

Employing Java language,

Explanation:

//for using stack data structure

import java.util.Stack;

//class definition

public class BracketMatch {

   //function to find the string is well formed or not

   public static boolean isWellFormed(String str) {

       //variable to store the character value

       char ch;

       //check if the first character itself is the end of the brackets

       if (str.charAt(0) == ')'||str.charAt(0) =='}'||str.charAt(0) ==']')

           return false;

       //creating a stack of character type

       Stack<Character> stack = new Stack<Character>();

       //iterating through the characters in string

       for(int i=0; i < str.length(); i++) {

           //storing the current character from the string in the variable

           ch = str.charAt(i);

           if(ch == '('||ch=='{'||ch=='[')

               //if the character is starting of the brackets push it into stack

               stack.push(ch);

           else if(ch == ')')

               //if it is closing bracket and the stack is empty then the string is not well formatted

               if(stack.empty())

                   return false;

               else if(stack.peek() == '(')

                   stack.pop();

               else

                   return false;

           else if(ch == '}')

               if(stack.empty())

                   return false;

               else if(stack.peek() == '{')

                   stack.pop();

               else

                   return false;

       }

       //returning the stack content, if the string will be well formed the stack would be empty

       //after all the operations

       return stack.empty();

   }

   //main method

   public static void main(String[] args) {

       //calling function to find if the string is welll formatted or not

       System.out.println(isWellFormed("{}"));

       //calling function to find if the string is welll formatted or not

       System.out.println(isWellFormed("([)]"));

   }

}