I call this brute force type approach we are replacing every () or {} or [] from the string with "" so therefore length of String is decreasing and if length of String doesn't change then i am simply breaking the loop otherwise if length of String gets down to 0 then it means everything in String is balanced otherwise not.
public class Question{
public static void main(String[] args) {
String target="{ [ ( ) ] }",target2="( ) [ ] { }",target3="[ ( ) ] ( ( ) )",target4="( { [ )";
target=target.replaceAll(" ","");
target2=target2.replaceAll(" ", "");
target3=target3.replaceAll(" ", "");
target4=target4.replaceAll(" ", "");
System.out.println(CheckExp(target));
System.out.println(CheckExp(target2));
System.out.println(CheckExp(target3));
System.out.println(CheckExp(target4));
}
public static Boolean CheckExp(String target) {
boolean flag = false;
if (target.length() < 2 || target.length()%2!=0 ) {
return flag;
}
int first,last;
while(true) {
first=target.length();
target = target.replace("()", "");
target = target.replace("{}","");
target = target.replace("[]","");
last=target.length();
if(first==last)
break;
flag= target.length() == 0;
}
return flag;
}
}