您的位置:首页 > 其它

网工没有过

2009-07-09 16:43 92 查看
/*
*下面的代码用于判断一个串中的括号是否匹配
所谓匹配是指不同类型的括号必须左右呼应,可以相互包含,但不能交叉

例如:
..(..[..]..)..  是允许的
..(...[...)....].... 是禁止的
对于 main 方法中的测试用例,应该输出:
false
true
false
false

*
*/
import java.util.*;
public class test20
{
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=='}')
{
//如果栈a为空,则可以直接返回false
if(a.empty()) return false;    // 填空
if(a.pop() != c) return false;
}
}
//循环结束,如栈a还有元素,则返回false
if(!a.empty()) 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("...(..[...].(.).){.(..)...."));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: