一、Java
- import java.util.Stack;
-
- class Solution {
- public boolean isValid(String s) {
- if (s.length() % 2 == 1) return false;
- Stack
stk = new Stack<>(); - for (char c : s.toCharArray()) {
- if (c == ')') {
- if (stk.isEmpty() || stk.pop() != '(') return false;
- } else if (c == ']') {
- if (stk.isEmpty() || stk.pop() != '[') return false;
- } else if (c == '}') {
- if (stk.isEmpty() || stk.pop() != '{') return false;
- } else {
- stk.push(c);
- }
- }
- return stk.isEmpty();
- }
- }
- import java.util.Stack;
-
- class Solution {
- public boolean isValid(String s) {
- if (s.length() % 2 == 1) return false;
- Stack
stk = new Stack<>(); - for(char c: s.toCharArray()) {
- if (c == '(') stk.push(')');
- else if(c == '[') stk.push(']');
- else if(c == '{') stk.push('}');
- else if(stk.isEmpty() || stk.pop() != c) return false;
- }
- return stk.isEmpty();
- }
- }
- import java.util.Stack;
-
- class Solution {
- public boolean isValid(String s) {
- if (s.length() % 2 == 1) return false;
- Stack
stk = new Stack<>(); - String leftStr = "([{", rightStr = ")]}";
- for (int i = 0; i < s.length(); i++) {
- int idx = rightStr.indexOf(s.charAt(i));
- if (idx != -1) {
- if (stk.isEmpty() || stk.pop() != leftStr.charAt(idx)) return false;
- } else {
- stk.push(s.charAt(i));
- }
- }
- return stk.isEmpty();
- }
- }
二、C++
- #include
- #include
-
- using namespace std;
-
- class Solution {
- public:
- bool isValid(string s) {
- if (s.length() % 2 == 1) return false;
- string leftStr = "([{", rightStr = ")]}";
- stack<char> stk;
- for (int i = 0; i < s.length(); i++) {
- auto idx = rightStr.find(s[i]); // 这里使用auto更好
- if (idx != string::npos) {
- if (stk.empty() || stk.top() != leftStr[idx]) return false;
- stk.pop();
- } else {
- stk.push(s[i]);
- }
- }
- return stk.empty();
- }
- };
三、Python
- class Solution:
- def isValid(self, s: str) -> bool:
- if len(s) % 2 == 1:
- return False
- stk = []
- m = {')': '(', ']': '[', '}': '{'}
- for c in s:
- if c in ')]}':
- if not stk or stk.pop() != m[c]: # not stk: len(stk) == 0
- return False
- else:
- stk.append(c)
- return not stk
四、JavaScript
- var isValid = function (s) {
- if (s.length % 2 === 1) return false;
- let stk = [];
- let m = {')': '(', ']': '[', '}': '{'};
- for (let i = 0; i < s.length; i++) {
- if (')]}'.indexOf(s[i]) !== -1) {
- if (stk.length === 0 || stk.pop() !== m[s[i]]) return false;
- } else {
- stk.push(s[i]);
- }
- }
- return stk.length === 0;
- };
五、Go
- package main
-
- import (
- "container/list"
- "strings"
- )
-
- func isValid(s string) bool {
- if len(s)%2 == 1 {
- return false
- }
- stk := list.New()
- m := map[uint8]uint8{')': '(', ']': '[', '}': '{'}
- for i := 0; i < len(s); i++ {
- if strings.ContainsRune(")]}", rune(s[i])) {
- if stk.Len() == 0 || stk.Remove(stk.Back()) != m[s[i]] {
- return false
- }
- } else {
- stk.PushBack(s[i])
- }
- }
- return stk.Len() == 0
- }