20. Valid Parentheses (Easy)

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

bool isValid(string s) {
    if (s.size() % 2) return false;

    stack<char> res;
    for (int i = 0; i < s.size(); ++i) {
        switch (s[i]) {
            case '(':
            case '[':
            case '{': res.push(s[i]); break;
            case ')': if (res.empty() || res.top() != '(') return false; 
                      else res.pop(); break;
            case ']': if (res.empty() || res.top() != '[') return false; 
                      else res.pop(); break;
            case '}': if (res.empty() || res.top() != '{') return false; 
                      else res.pop(); break;
        }
    }
    return res.empty();
}

bool isValid(string s) {
    stack<char> parentheses;
    for (int i = 0; i < s.size(); ++i) {
        if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]);
        else {
            if (parentheses.empty()) return false;
            if (s[i] == ')' && parentheses.top() != '(') return false;
            if (s[i] == ']' && parentheses.top() != '[') return false;
            if (s[i] == '}' && parentheses.top() != '{') return false;
            parentheses.pop();
        }
    }
    return parentheses.empty();
}

results matching ""

    No results matching ""