Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created September 16, 2016 14:56
Show Gist options
  • Save nichtemna/4f08cd4577ffde146e9969cafc9644cd to your computer and use it in GitHub Desktop.
Save nichtemna/4f08cd4577ffde146e9969cafc9644cd to your computer and use it in GitHub Desktop.
Balanced parenthesis Create function that will determine are the parenthesis balanced in a given string
public class BalacedBrackets {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
String s = in.next();
getResult(s);
}
}
private static void getResult(String text){
int wrong_position = -1;
Stack<Bracket> opening_brackets_stack = new Stack<Bracket>();
for (int position = 0; position < text.length(); ++position) {
char next = text.charAt(position);
if (next == '(' || next == '[' || next == '{') {
opening_brackets_stack.add(new Bracket(next, position));
}
if ((next == ')' || next == ']' || next == '}')) {
if (!opening_brackets_stack.empty()) {
Bracket pop = opening_brackets_stack.pop();
if (!pop.Match(next)) {
wrong_position = position + 1;
break;
}
} else {
wrong_position = position + 1;
break;
}
}
}
if (wrong_position == -1 && opening_brackets_stack.empty()) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
class Bracket {
Bracket(char type, int position) {
this.type = type;
this.position = position;
}
boolean Match(char c) {
if (this.type == '[' && c == ']')
return true;
if (this.type == '{' && c == '}')
return true;
if (this.type == '(' && c == ')')
return true;
return false;
}
char type;
int position;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment