Skip to content

Instantly share code, notes, and snippets.

@wulfgarpro
Created March 7, 2012 10:03
Show Gist options
  • Save wulfgarpro/1992341 to your computer and use it in GitHub Desktop.
Save wulfgarpro/1992341 to your computer and use it in GitHub Desktop.
Parenthesis matching in Java
package uni.rev.q0;
import java.util.Stack;
public class q0 {
static class Parenthesis {
private char parenthesis;
private int position;
public Parenthesis(char par, int pos) {
this.parenthesis = par;
this.position = pos;
}
@Override
public String toString() {
return this.parenthesis + " from position: " + this.position;
}
}
public static void main(String[] args) {
String data = "((())())(";
char[] chars = data.toCharArray();
Stack<Parenthesis> s = new Stack<Parenthesis>();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '(') {
s.push(new Parenthesis('(', i + 1));
} else if (chars[i] == ')') {
if (!s.isEmpty()) {
s.pop();
} else {
System.out.println(") from position: " + (i + 1));
return;
}
}
}
if (!s.isEmpty()) {
for (int i = 0; i < s.size(); i++) {
System.out.println(s.pop());
}
} else {
System.out.println("No errors!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment