import org.apache.commons.collections.ArrayStack;
import org.apache.commons.collections.functors.WhileClosure;
public class KuohaopiPei {
public static void main(String[] args)
{
print("(a(a(aaaa(a)");
}
public static void print(String exrt)
{
ArrayStack s = new ArrayStack();
int leng = exrt.length();
for (int i = 0; i < leng; i++) {
if (exrt.charAt(i)=='(') {
s.push(new Integer(i));
}
if (exrt.charAt(i)==')') {
try {
System.out.println("match "+s.pop()+" "+i);
} catch (Exception e) {
System.out.println("No match for right ) at"+i);
// TODO: handle exception
}
}
}
while (!s.empty()){
System.out.println("no match at left at"+s.pop());
}
}
}
package 括号匹配;
import java.util.Stack;
public class ParenthesisMatching
{
public boolean check(String str)
{
Stack<Character> stack = new Stack<Character>();
boolean flag = true;
for (int i = 0; i < str.length() && flag; i++)
{
try
{
switch (str.charAt(i))
{
case '(':
case '[':
case '{':
stack.push(str.charAt(i));
break;
case ')':
if (stack.pop() != '(')
flag = false;
break;
case ']':
if (stack.pop() != '[')
flag = false;
break;
case '}':
if (stack.pop() != '{')
flag = false;
break;
}
}
catch (Exception e)
{
flag = false;
}
}
if (flag && !stack.isEmpty())
flag = false;
return flag;
}
public static void main(String[] args)
{
ParenthesisMatching pm = new ParenthesisMatching();
System.out.println("(): " + pm.check("()"));
System.out.println("a(bc[d])e{fd}: " + pm.check("a(bc[d])e{fd}"));
System.out.println("a(bc]d: " + pm.check("a(bc]d"));
System.out.println("a(b(c)d: " + pm.check("a(b(c)d"));
System.out.println("a(b)c)d: " + pm.check("a(b)c)d"));
}
}