LeetCode----- 20.Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

由于只包含字符的字符串'('')''{''}''['']',确定输入字符串是有效的。

括号匹配思路:

1.循环遍历数组,扫描每个字符;

2.判断当前字符,如果是左括号符号时,将该字符压入栈中;

3.判断当前字符如果是右括号符号时,弹出栈顶符号;

4.然后栈顶元素与当前字符进行匹配,如果不匹配,返回false,如果匹配继续下一字符的扫描。

5.扫描结束后,判断当前栈中是否还有元素,如果为空,返回true,表明匹配成功;如果不为空,则返回false,表明匹配失败。

public boolean isValid(String s) {
    	if(s.length() % 2 != 0) {
    		return false;
    	}
    	Stack<Character> stack = new Stack<Character>();
    	char[] code = s.toCharArray();

    	for (int i = 0; i < code.length; i++) {

    		if(code[i]=='(' || code[i] == '{' || code[i] == '[') {
    			stack.push(code[i]);
    		}
    		if(code[i]==')' || code[i] == '}' || code[i] == ']') {
    			if(!stack.isEmpty()) {
           			Character c = stack.pop();
        			if((c == null)||(!match(c,code[i]))) {
        				return false;
        			}
    			}
    		}
		}
    	if(stack.isEmpty()) {
    		return true;
    	}else {
			return false;
		}
    }
	

	public boolean match(char left,char right)
	{
		boolean ret = false;
		
		switch(left)
		{
			case '[':  ret = (right == ']');  break;
			case '(':  ret = (right == ')');  break;
			case '{':  ret = (right == '}');  break;
			default:
				ret = false;
				break;
		}
		
		return ret;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值