156k views
4 votes
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.

User Naved Khan
by
7.9k points

1 Answer

2 votes

Answer:

Employing Java language,

Step-by-step 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) ==']')

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=='')

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("([)]"));

}

}

User Millenomi
by
8.1k points