Verify bracket sequence is valid or not

Verify bracket sequence is valid or not.
We have given string of brackets and we need to find either its valid or not.
For this we need to check the string once by one. and compare each character with this, so if its open bracket will add this to stack and if its closed bracket so pop the to entry from stack and add both character and match with the string bracket.


public class BracketSequance {

public static void main(String[] args) {

String str  = "(){([])}";
System.out.println(validateSequance(str));
}

private static String validateSequance(String str) {
String result = "valid";
char openB = '(';
char openM = '{';
char openD = '[';

String strB = "()";
String strM = "{}";
String strD = "[]";

Stack<Character> stack = new Stack<>();
//int counter = 0;
for(int i=0;i<str.length();i++) {
if(str.charAt(i) == openB || str.charAt(i) == openD || str.charAt(i) == openM) {
stack.push(str.charAt(i));
//counter++;
}else {
if(!stack.isEmpty()) {
char temp =stack.peek();
char tA = str.charAt(i);
String rr = String.valueOf(temp)+String.valueOf(tA);
if(strB.equals(rr) || strD.equals(rr) || strM.equals(rr)) {
stack.pop();
}else {
result = "not valid";
}
}else {
result = "not valid";
}
}
}
//System.out.println(counter);
return result;
}

}

Post a Comment

Previous Post Next Post