Accept a sentence terminated by ‘.’, ‘?’ or ‘!’ only. Sentence may contain any of () [] {} plus letters/spaces. It must contain no digits and no other symbols besides the final terminator. For any violation, display INVALID INPUT.
Perform the following tasks:
(a) Check if the brackets are balanced and properly nested.
(b) Print the maximum nesting depth of brackets.
(c) If unbalanced, print the index (one-based indexing) of the first error.
- A mismatched/extra closing bracket is an error at that bracket’s index.
- If brackets are incomplete at the terminator, the first error is the index of the first bracket that cannot be matched (typically where the mismatch first occurs).
Test your program for the following data and some random data:
Example 1
INPUT: This (is [very {deep}]) indeed!
OUTPUT:
BALANCED: YES
MAX DEPTH: 3
Example 2
INPUT: Simple () test.
OUTPUT:
BALANCED: YES
MAX DEPTH: 1
Example 3
INPUT: Hello world.
OUTPUT:
BALANCED: YES
MAX DEPTH: 0
Example 4
INPUT: We love (balanced [brackets)!
OUTPUT:
BALANCED: NO
ERROR AT INDEX: 28
Example 5
INPUT: Hi #there!
OUTPUT: INVALID INPUT
import java.util.Scanner;
class Brackets{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Sentence: ");
String s = in.nextLine().trim();
if(s.length() == 0){
System.out.println("INVALID INPUT");
return;
}
char last = s.charAt(s.length() - 1);
if(".?!".indexOf(last) == -1){
System.out.println("INVALID INPUT");
return;
}
s = s.substring(0, s.length() - 1);
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(!Character.isLetter(ch) && ch != ' ' && "({[]})".indexOf(ch) == -1){
System.out.println("INVALID INPUT");
return;
}
}
char stack[] = new char[s.length()];
int top = -1;
int maxDepth = 0;
int errorIndex = -1;
boolean errorFound = false;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if("({[".indexOf(ch) >= 0){
stack[++top] = ch;
if(top + 1 > maxDepth)
maxDepth = top + 1;
}
else if(")}]".indexOf(ch) >= 0){
if(top == -1){
errorFound = true;
errorIndex = i + 1;
break;
}
else{
char open = stack[top];
if((open == '[' && ch == ']') || (open == '{' && ch == '}') || (open == '(' && ch == ')'))
top--;
else{
errorFound = true;
errorIndex = i + 1;
break;
}
}
}
}
if(top != -1)
errorFound = true;
if(errorFound){
System.out.println("BALANCED: NO");
System.out.println("ERROR AT INDEX: " + errorIndex);
}
else{
System.out.println("BALANCED: YES");
System.out.println("MAX DEPTH: " + maxDepth);
}
}
}