`
shixy
  • 浏览: 141219 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
压栈({)和出栈(} 华为面试题!
import java.util.LinkedList;

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

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

	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;
	}
}
Global site tag (gtag.js) - Google Analytics