题目描述
给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return bool布尔型
*/
Stack<Character>stack=new Stack<>();
public boolean isValid (String s) {
// write code here
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();
}
}