java括号匹配

 
package com.duapp.itfanr;

public class CharDemo{
	public static boolean isMatch(String value) {
		int numCount = 0, numMatch = 0;
		for (int i=0; null != value && i<value.length(); i++) {
			char ch = value.charAt(i);
			if (ch == '{') {
				numCount ++;
				numMatch ++;
			} else if (ch == '}') {
				numCount --;
			}
			if (numCount < 0) {
				return false;
			}
		}

		return (numMatch > 0 && numCount == 0);
	}

	public static void main(String args[])  {
		System.out.println( "=========must false=====" );
		System.out.println( isMatch(null) );
		System.out.println( isMatch("") );
		System.out.println( isMatch("ddddd") );
		System.out.println( isMatch("d{dddd") );
		System.out.println( isMatch("dd{}}ddd") );
		System.out.println( isMatch("d}dd{dd") );

		System.out.println( "=========must true=====" );
		System.out.println( isMatch("dd{}ddd") );
		System.out.println( isMatch("ddd{{}d}d") );
		System.out.println( isMatch("d{d{d}d}d") );
	}
}
 
package com.duapp.itfanr;

import java.util.LinkedList;

public class CharDemo
{
	private LinkedList<Character> stack = new LinkedList<Character>();

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		CharDemo matcher = new CharDemo();
		System.out.println(matcher.matches("{{{{}}a}ab}}"));
	}

	public boolean matches(String string)
	{
		if (string == null || string.length() == 0 || string.trim().equals(""))
			return true;
		int i = 0;
		while (i < string.length())
		{
			char ch = string.charAt(i);
			if (ch == '{')
			{
				stack.push(ch);
			}
			else if (ch == '}')
			{
				if (stack.isEmpty())
					return false;
				stack.pop();
			}
			i++;
		}

		if (!stack.isEmpty())
			return false;
		return true;
	}
}
参考: [1]. http://www.iteye.com/topic/1055854

转载于:https://my.oschina.net/itfanr/blog/195704

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值