diff --git "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\220\210\346\263\225\346\213\254\345\217\267\345\210\244\345\256\232.md" "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\220\210\346\263\225\346\213\254\345\217\267\345\210\244\345\256\232.md" index 32239bdae460f4d342f1a499bb0ecfb3839e9df6..3bded5a32287cfec435f1237c974e563702c9e98 100644 --- "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\220\210\346\263\225\346\213\254\345\217\267\345\210\244\345\256\232.md" +++ "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\220\210\346\263\225\346\213\254\345\217\267\345\210\244\345\256\232.md" @@ -112,4 +112,28 @@ char leftOf(char c) {

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +```java +//基本思想:每次遇到左括号时都将相对应的右括号')',']'或'}'推入堆栈 +//如果在字符串中出现右括号,则需要检查堆栈是否为空,以及顶部元素是否与该右括号相同。如果不是,则该字符串无效。 +//最后,我们还需要检查堆栈是否为空 +public boolean isValid(String s) { + Deque stack = new ArrayDeque<>(); + for(char c : s.toCharArray()){ + //是左括号就将相对应的右括号入栈 + if(c=='(') { + stack.offerLast(')'); + }else if(c=='{'){ + stack.offerLast('}'); + }else if(c=='['){ + stack.offerLast(']'); + }else if(stack.isEmpty() || stack.pollLast()!=c){//出现右括号,检查堆栈是否为空,以及顶部元素是否与该右括号相同 + return false; + } + } + return stack.isEmpty(); +} + +``` +