Here is the thing:
You are given a string whose elements are brackets ( ) [ ] { }
.
Rules:
Every opening bracket has a corresponding closing bracket.
2 brackets form a pair if they have no open bracket of any type between them.
The closing bracket of a pair must be of the same as the opening bracket, e.g.
()
is valid, but[)
is not valid.
The task is to determine if a string of bracket is valid or invalid by these criteria.
example valid string: {}[]()
example invalid string: {[}]
This is my solution:
static String braces(String string) {
Stack<String> stack = new Stack<>();
for(int i = 0; i <= string.length() - 1; i ++){
if(string.substring(i, i+1).equals("("))
stack.push((string.substring(i, i+1)));
else if(string.substring(i, i+1).equals("["))
stack.push((string.substring(i, i+1)));
else if(string.substring(i, i+1).equals("{"))
stack.push((string.substring(i, i+1)));
else if(string.substring(i, i+1).equals(")"))
if(stack.peek().equals("("))
stack.pop();
else
return "NO";
else if(string.substring(i, i+1).equals("]"))
if(stack.peek().equals("["))
stack.pop();
else
return "NO";
else if(string.substring(i, i+1).equals("}"))
if(stack.peek().equals("{"))
stack.pop();
else
return "NO";
}
return "YES";
}
It is done according to algorithm from here How to find validity of a string of parentheses, curly brackets and square brackets? which is as follows:
- Maintain a stack of characters.
- Whenever you find opening braces '(', '{' OR '[' push it on the stack.
- Whenever you find closing braces ')', '}' OR ']' , check if top of stack is corresponding opening bracket, if yes, then pop the stack, else break the loop and return false.
- Repeat steps 2 - 3 until end of the string.
But I don't like how does it look like. The way of accessing to String elements is kind of clunky and I'm curious if there is another, more clear way to solve the problem, maybe using regular expression?