Skip to content

Instantly share code, notes, and snippets.

@otykhonruk
Created November 7, 2012 14:22
Show Gist options
  • Save otykhonruk/4031886 to your computer and use it in GitHub Desktop.
Save otykhonruk/4031886 to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
public class ParenCheck {
static int OPENING = 1, CLOSING = -1;
static int PAREN = 0, BRACKET = 1, BRACE = 2, PAIRING = 3;
static String[] desc = { "()", "[]", "{}", "Pairing" };
static int[] check(char[] s) {
int[] stat = new int[4];
int sym, type;
LinkedList<Integer> stack = new LinkedList<Integer>();
for(int i=0; i<s.length; i++) {
switch(s[i]) {
case '(': sym = PAREN; type = OPENING; break;
case ')': sym = PAREN; type = CLOSING; break;
case '[': sym = BRACKET; type = OPENING; break;
case ']': sym = BRACKET; type = CLOSING; break;
case '{': sym = BRACE; type = OPENING; break;
case '}': sym = BRACE; type = CLOSING; break;
default: continue;
}
stat[sym] += type;
if(type == OPENING) {
stack.push(sym);
} else {
if(!stack.isEmpty() && stack.peek() == sym)
stack.pop();
else
stat[PAIRING]++;
}
}
stat[PAIRING] += stack.size();
return stat;
}
public static void main(String[] args) {
if(args.length > 0) {
int[] stat = check(args[0].toCharArray());
for(int i=0; i<stat.length; i++)
System.out.format("%s errors: %d\n", desc[i], Math.abs(stat[i]));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment