Generate all bracket combination, check if brackets open and closing is correct or not
https://github.com/mission-peace/interview/blob/master/src/com/interview/recursion/Bracketology.java
public void bracketPermutation(char result[],int n, int pos,int openCount,int closeCount){
if(pos == 2*n){
printArray(result);
return;
}
if(openCount < n){
result[pos] = '(';
bracketPermutation(result, n, pos+1,openCount+1,closeCount);
}
if(closeCount < openCount){
result[pos] = ')';
bracketPermutation(result, n, pos+1, openCount, closeCount+1);
}
}
public boolean matchBracket(char []brackets){
Deque<Character> stack = new LinkedList<Character>();
for(Character ch : brackets){
char checkChar = getOpeningCharacter(ch);
if(checkChar == 0){
stack.addFirst(ch);
}else{
if(stack.size() == 0 || stack.peek() != checkChar){
return false;
}else{
stack.pop();
}
}
}
if(stack.size() > 0){
return false;
}
return true;
}
private Character getOpeningCharacter(char ch){
switch(ch){
case ')' : return '(';
case ']' : return '[';
case '}' : return '{';
default : return 0;
}
}
https://github.com/mission-peace/interview/blob/master/src/com/interview/recursion/Bracketology.java
public void bracketPermutation(char result[],int n, int pos,int openCount,int closeCount){
if(pos == 2*n){
printArray(result);
return;
}
if(openCount < n){
result[pos] = '(';
bracketPermutation(result, n, pos+1,openCount+1,closeCount);
}
if(closeCount < openCount){
result[pos] = ')';
bracketPermutation(result, n, pos+1, openCount, closeCount+1);
}
}
public boolean matchBracket(char []brackets){
Deque<Character> stack = new LinkedList<Character>();
for(Character ch : brackets){
char checkChar = getOpeningCharacter(ch);
if(checkChar == 0){
stack.addFirst(ch);
}else{
if(stack.size() == 0 || stack.peek() != checkChar){
return false;
}else{
stack.pop();
}
}
}
if(stack.size() > 0){
return false;
}
return true;
}
private Character getOpeningCharacter(char ch){
switch(ch){
case ')' : return '(';
case ']' : return '[';
case '}' : return '{';
default : return 0;
}
}