Skip to content

Latest commit

 

History

History
81 lines (70 loc) · 1.58 KB

20.-valid-parentheses.md

File metadata and controls

81 lines (70 loc) · 1.58 KB

20. Valid Parentheses

{% tabs %} {% tab title="CPP" %}

class Solution {
public:
    bool isValid(string s) {
        if (s.size()%2 == 1) return false;

        unordered_map<char, char> pairs = {
            {'(', ')'},
            {'[', ']'},
            {'{', '}'}
        };

        stack<char> stack;
        for (char c : s){
            if (!stack.empty() && pairs[stack.top()] == c) {
                stack.pop();
            } else {
                stack.push(c);
            }
        }
        return stack.empty();
    }
};

{% endtab %}

{% tab title="Go" %}

func isValid(s string) bool {
    if len(s) == 0 {
        return true
    }
    d := make(map[string]string)
    d["("]=")"
    d["["]="]"
    d["{"]="}"
    stack := make([]string,0)
    stack = append(stack,string(s[0]))
    var i int // 不能循环内定义
    for i = 1; i<len(s);i++{
        if len(stack)!=0 && string(s[i]) == d[stack[len(stack)-1]]{
        stack = stack[:len(stack)-1]
        
        }else{
            stack = append(stack,string(s[i]))
        }       
    }
    return len(stack) == 0
}

{% endtab %}

{% tab title="Python" %}

class Solution:
    def isValid(self, s: str) -> bool:
        if not s :return True
        d = {
            "(":")",
            "[":"]",
            "{":"}",
        }
        
        stack = [s[0]]
        
        for i in range(1,len(s)):
            if stack and s[i] == d.get(stack[-1]):
                stack.pop()
            else:
                stack.append(s[i])
            
        return len(stack) == 0

{% endtab %} {% endtabs %}