diff --git "a/notes/LeetCode\347\254\25420\345\217\267\351\227\256\351\242\230\357\274\232\346\234\211\346\225\210\347\232\204\346\213\254\345\217\267.md" "b/notes/LeetCode\347\254\25420\345\217\267\351\227\256\351\242\230\357\274\232\346\234\211\346\225\210\347\232\204\346\213\254\345\217\267.md" index c4d0c9c4646a641e78ee6011ff847861d06d66ff..712e034754218de9194d1e7fcbae4221e041b840 100644 --- "a/notes/LeetCode\347\254\25420\345\217\267\351\227\256\351\242\230\357\274\232\346\234\211\346\225\210\347\232\204\346\213\254\345\217\267.md" +++ "b/notes/LeetCode\347\254\25420\345\217\267\351\227\256\351\242\230\357\274\232\346\234\211\346\225\210\347\232\204\346\213\254\345\217\267.md" @@ -71,7 +71,8 @@ ### 代码实现 -``` +#### C++ +```c++ class Solution { public: bool isValid(string s) { @@ -109,7 +110,52 @@ public: } }; ``` +#### Java +```java +class Solution { + public boolean isValid(String s) { + //String open="({["; + //String close="]})"; + + Stack stack = new Stack(); + + if(s.length() % 2 != 0) + return false; + + + for (char c : s.toCharArray()) + { + if (c == '(') stack.push(')'); + else if (c == '{') stack.push('}'); + else if (c == '[') stack.push(']'); + else if (stack.isEmpty() || stack.pop() != c) return false; + } + + return stack.isEmpty(); + } + +} +``` +#### Python +```python +class Solution(object): + def isValid(self, s): + open_list = ["[", "{", "("] + close_list = ["]", "}", ")"] + stack = [] + + for i in s: + if i in open_list: + stack.append(i) + elif i in close_list: + pos=close_list.index(i) + if len(stack)>0 and (open_list[pos] == stack[len(stack)-1]): + stack.pop() + else: + return False + if len(stack) == 0: + return True +``` - -![](https://blog-1257126549.cos.ap-guangzhou.myqcloud.com/blog/gkcza.png) \ No newline at end of file +![](https://blog-1257126549.cos.ap-guangzhou.myqcloud.com/blog/gkcza.png)