codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Leetcode] Valid Parentheses #2

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago

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

An input string is valid if:

Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.

Example 1:

Input: "()" Output: true Example 2:

Input: "()[]{}" Output: true Example 3:

Input: "(]" Output: false Example 4:

Input: "([)]" Output: false Example 5:

Input: "{[]}" Output: true

lpatmo commented 5 years ago

https://repl.it/@lpatmo/ExcellentBlandAutocad Javascript:


/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    if (s.length === 0) {
        return true;
    }
    //create new string
    //once you find a character that's open bracket, add that to new string
    //if you find a closing bracket, compare that to most recent element in string
    // if they match, you remove that element from string
    // if they don't match, return false. 
    //at the end of it, if string is empty, return true
    var stack = ""
    var opening = "{(["
    var closing = "})]"
    for (var i = 0; i < s.length; i++) { // looping through 
        if (opening.indexOf(s[i]) > -1) { //if we find an opening bracket
            stack += s[i]; //add to "stack"
        } else if (stack.length === 0) { //if the element is a closing bracket, AND no opening brackets exist for it to compare to, return false 
            return false;
        } else {
            //find index of closing bracket, compare to index of opening
            //check if the closing bracket matches w/ the last element of the "stack"
           if (closing.indexOf(s[i]) === opening.indexOf(stack[stack.length-1])) {
               stack = stack.slice(0, stack.length-1); //if there is a match, pop the stack
           } else {
               return false;
           }   
        }
    }
    return stack.length === 0;    
};