Valid Parentheses (1) - JavaScript

Question

Given a string of parentheses "{", "}", check if the string is valid parentheses. The brackets must close in the correct order. E.g.: "{{}}" is valid, "}{}{" is not valid.


Solution

// Time complexity: O(n)
function isValidParentheses(str) {
    var i = 0, l = str.length, arr = [];
    if (!l) {
        return true;
    }

    if ((l % 2) !== 0) {
        return false;
    }

    while (i < l) {
        var s = str[i];
        if (s == "{") {
            arr.push(s);
        } else if (s == "}") {
            if (arr.length) {
                arr.pop();
            } else {
                return false;
            }
        }
        i++;
    }
    return true;
}

isValidParentheses("{{{}}}"); // true
isValidParentheses("{{}{}}"); // true
isValidParentheses("{}{{}}"); // true
isValidParentheses("}{}{"); // false

Demo

Yang Zhao

Read more posts by this author.


Comment