一.問題描述
給定一個只包括 '(',')','{','}','[',']' 的字符串 s ,判斷字符串是否有效。
有效字符串需滿足:
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
示例 1:
輸入:s = "()"
輸出:true
二.示例代碼
private static final Map<Character, Character> map = new HashMap<Character, Character>() {{
? ? ? ? put('{', '}');
? ? ? ? put('[', ']');
? ? ? ? put('(', ')');
? ? }};
? ? public static void main(String[] args) {
? ? ? ? String s = "()[]{}{}";
? ? ? ? Boolean result = validBrackets(s);
? ? ? ? System.out.println(result);
? ? }
? ? private static Boolean validBrackets(String str) {
? ? ? ? if (StringUtils.isEmpty(str)) {
? ? ? ? ? ? return false;
? ? ? ? }
? ? ? ? Stack<Character> stack = new Stack<>();
? ? ? ? for (int i = 0; i < str.length(); i++) {
? ? ? ? ? ? char c = str.charAt(i);
? ? ? ? ? ? if (map.containsKey(c)) {
? ? ? ? ? ? ? ? stack.push(c);
? ? ? ? ? ? }
? ? ? ? ? ? if (map.containsValue(c)) {
? ? ? ? ? ? ? ? if (stack.empty()) {
? ? ? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? if (!map.get(stack.pop()).equals(c)) {
? ? ? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? if (!stack.empty()) {
? ? ? ? ? ? return false;
? ? ? ? }
? ? ? ? return true;
? ? }