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.

 

括号匹配~我自己考虑到类似小括号包含中括号([])或者中括号包含大括号的情况可能是不正确的,但实际没有影响~不用额外考虑这样的情况,只有括号匹配即可。

phoenix13steve  解法

public boolean isValid(String s) {
	Stack<Character> stack = new Stack<Character>();
	for (char c : s.toCharArray()) {//遍历方式简洁
		if (c == '(')
			stack.push(')');
		else if (c == '{')
			stack.push('}');
		else if (c == '[')
			stack.push(']');
		else if (stack.isEmpty() || stack.pop() != c)//之前存储对应的括号,此处直接比较是否相等
			return false;
	}
	return stack.isEmpty();
}

 

 

 

我的代码

class Solution {
public boolean isValid(String s) {
if(s.isEmpty())
return true;
Stack<Character> C = new Stack<Character>();
char now = '(';
char last = ')';
for (int i = 0; i < s.length(); i++) {
now = s.charAt(i);
if ((now == '(') || (now == '[') || (now == '{'))
C.push(now);
else {
if (C.isEmpty())
return false;
last = C.pop();
if ((now == ')') && (last != '('))
return false;
if ((now == ']') && (last != '['))
return false;
if ((now == '}') && (last != '{'))
return false;
}
}
if (C.isEmpty())
return true;
return false;


}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值