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
2007-08-07 16:12:44
·
answer #1
·
answered by McFate 7
·
0⤊
0⤋
McFate covered it pretty well, but if you intend to actually use this, there is MUCH more to be done. You will also want to exclude parens that are in quoted strings ( and possibly other exclusions, depending on your language.) And you do NOT want to exclude a quote in a string if it is escaped. You will also need to couple paren matching with block containment. For example:
BEGIN
(statement
END
)
should probably NOT be considered well matched parens. It really becomes a major parsing effort to do completely, but you can write a single pass with something like McFate showed, adding a facility for string exclusion, and make it recursive. Recurse down at the start of each block start and at each block end fail if mismatched in that block, else return back up. The whole program is of course treated as a block. When *that* block returns your parens are successfully matched.
When you get that much done, you will be fairly complete and probably have sufficient framework to add on whatever you discover is still needed.
Hope this helps.
2007-08-07 18:22:26
·
answer #2
·
answered by oldguy 4
·
1⤊
0⤋
You're going to have to implement a stack. Then when you find a closing parenthesis... check to make sure it matches with the last item in the stack. If it does... pop the stack. If items are at the end, then it is not syntactically correct.
2007-08-07 14:47:02
·
answer #3
·
answered by marleymang 2
·
0⤊
0⤋