括号问题
编写代码用于判断一个串中的括号是否匹配。
所谓匹配是指不同类型的括号必须左右呼应,可以相互包含,但不能交叉。
若匹配,则输出 true,否则输出 false。
例如:
…(…[…]…)… 是允许的;
…(…[…)…]… 是禁止的。
AC代码
import java.util.*;
public class Main
{
public static boolean isGoodBracket(String s)
{
Stack<Character> a = new Stack<Character>();
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if(c=='(') a.push(')');
if(c=='[') a.push(']');
if(c=='{') a.push('}');
if(c==')' || c==']' || c=='}')
{
if(a.isEmpty()) return false; //有后括号却没有前括号匹配
if(a.pop() != c) return false; //检验括号顺序
}
}
if(!a.isEmpty()) return false; //有前括号却没有后括号匹配
return true;
}
public static void main(String[] args)
{
System.out.println( isGoodBracket("...(..[.)..].{.(..).}..."));
System.out.println( isGoodBracket("...(..[...].(.).){.(..).}..."));
System.out.println( isGoodBracket(".....[...].(.).){.(..).}..."));
System.out.println( isGoodBracket("...(..[...].(.).){.(..)...."));
}
}