题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return bool布尔型
(,),{,},[,]
*/
public boolean isValid (String s) {
// write code here
Stack<Character> stack=new Stack<>();
char str[]=s.toCharArray();
for(int i=0;i<s.length();i++){
if(str[i]=='('){
stack.push(')');
}else if(str[i]=='{'){
stack.push('}');
}else if(str[i]=='['){
stack.push(']');
//如果字符串还没有遍历完,结果栈为空,说明有单独的括号,则返回false
}else if(stack.isEmpty()||str[i]!=stack.pop()){
return false;
}
}
//遍历完以后如果栈为空,说明无单独符号
if(stack.isEmpty()){
return true;
//否则有单独符号
}else{
return false;
}
}
}
