Hello guys, Let's continue our algorithm series...
Today i am going to show you how to solve valid Brackets problem. Let's discuss this problem first.
In this problem we are given brackets in form of String.We have to find out if they are valid or not.
Example
{([])} : Valid
{(}} : Invalid
{(} : Invalid
{ : Invalid
} : Invalid
{([)]} : Invalid
Let's see the solution.
public boolean validBrackets(String brackets) {
char[] arr = brackets.toCharArray();
Stack<Character> stack = new Stack<>();
for (Character ch : arr) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else {
if (stack.isEmpty()) {
return false;
} else {
if (
ch == ')' && stack.peek() == '(' ||
ch == '}' && stack.peek() == '{' ||
ch == ']' && stack.peek() == '['
){
stack.pop();
}else{
return false;
}
}
}
}
return stack.isEmpty();
}
Hope this post was useful. Thank you ❤.
Top comments (0)