As long as you're not trying to actually parse anything, you can just keep a count. Start at 0 when you start going through the input character by character. Every time you see an open parenthesis, add 1. Every time you see a closed parenthesis, subtract 1.
If the number ever goes negative, it's an error (a closing parenthesis without a matching opening). If you hit the end of the string and the number isn't zero, then there's a mismatch between open and closed.
=================
public class MyClass {
static String parenMatch(String s) {
int count = 0;
for (int i=0; i
char c = s.charAt(i);
if (c == '(') count++;
else if (c == ')') {
count--;
if (count < 0) return "Unmatched closed paren";
} }
if (count > 0) return "" + count + " unmatched open paren(s)";
return null;
}
public static void main(String[] args) {
String s = "(foo bar) (( bletch)";
System.out.println(s + " -> " + parenMatch(s));
s = "(foo bar) ) oops";
System.out.println(s + " -> " + parenMatch(s));
s = "(foo bar) (bletch)";
System.out.println(s + " -> " + parenMatch(s));
} }
=================
Sample output:
(foo bar) (( bletch) -> 1 unmatched open paren(s)
(foo bar) ) oops -> Unmatched closed paren
(foo bar) (bletch) -> null