题解 | #有效括号序列#
有效括号序列
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 String begin = "({["; String end = ")}]"; Stack<Character> t = new Stack<>(); for (char c :s.toCharArray()){ if (begin.indexOf(c) != -1){ t.push(c); continue; } if (end.indexOf(c) != -1){ if (t.empty()) { return false; } Character pop = t.pop(); switch (c){ case ')': if (!pop.equals('(')){ return false; } break; case ']': if (!pop.equals('[')){ return false; } break; case '}': if (!pop.equals('{')){ return false; } break; default: break; } } } if (t.empty()){ return true; }else { return false; } } }
使用栈存储字符串中出现的括号开始字符,遇到结束字符依次出栈,判读出栈的字符是否匹配。