题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { if(s.length() <= 1){ return false; } Map<Character,Character> map = new HashMap();//使用map集合作为规则匹配器 map.put('(',')'); map.put('{','}'); map.put('[',']'); Stack stack = new Stack();//使用栈进行规则匹配 for(int i = 0; i < s.length(); i++){//遍历字符串 char c = s.charAt(i);//获取每个字符 if(map.containsKey(c)){//如果该 stack.push(c); }else if(map.containsValue(c)){ if(!stack.isEmpty()){ if(map.get(stack.pop()) == c){ continue; } } return false; }else{ return false; } } if(!stack.isEmpty()){ return false; } return true; } }