题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return bool布尔型
*/
// Try to solve it with Stack
Stack<Character> st = new Stack<Character>();
public boolean isValid (String s) {
// write code here
for(int i=0;i<s.length();i++){
System.out.println(s.charAt(i));
if(st.isEmpty()){
if(s.charAt(i)==')' || s.charAt(i)==']' || s.charAt(i)==']')
return false;
}
else if(s.charAt(i)==')'&st.peek()=='(') {
st.pop();
continue;
}
else if(s.charAt(i)==']'&st.peek()=='[') {
st.pop();
continue;
}
else if(s.charAt(i)=='}'&st.peek()=='{') {
st.pop();
continue;
}
st.push(s.charAt(i));
}
if(st.isEmpty()) return true;
return false;
}
}
不如答案来的简洁,不过栈的思路是自己想的
if语句的嵌套要注意{},否则后续的else if 有可能会跟子if语句变成平行关系。

