Given an expression string x. Examine whether the pairs and the orders of {,},(,),[,]
are correct in exp.
For example, the function should return 'true' for exp = [()]{}{[()()]()}
and 'false' for exp = [(])
.
I am using an ArrayList to solve that. But I'm getting an ArrayIndexOutOfBoundsException.
Note: It can be implemented by Stack but I want to know the solution using my approach.
This is what I tried to do:
class Solution {
//Function to check if brackets are balanced or not.
static boolean ispar(String x) {
int n = x.length();
boolean sol = false;
ArrayList < Character > store = new ArrayList < Character > ();
if (n % 2 != 0 && x.charAt(0) == ')' && x.charAt(0) == '}' && x.charAt(0) == ']') {
sol = false;
} else {
for (int i = 0; i < n; i++) {
if (x.charAt(i) == '[') {
store.add('[');
store.add(']');
}
if (x.charAt(i) == '{') {
store.add('{');
store.add('}');
}
if (x.charAt(i) == '(') {
store.add('(');
store.add(')');
}
if (x.charAt(i) == ')') {
store.remove(')');
store.remove('(');
}
if (x.charAt(i) == '}') {
store.remove('}');
store.remove('{');
}
if (x.charAt(i) == ']') {
store.add(']');
store.add('[');
}
}
if (store.size() == 0) {
sol = true;
}
}
return sol;
// add your code here
}
}