Valid Parenthesis - Java script
56
Dec 19, 2020
Dec 19, 2020

I also persued a solution where even odd modulo of indices of the Parenthesis could be used, for example
if first { occurred at even then the closing } would only occur at odd and vice versa, offcourse I had to check next opening and closing to accommodate if there are multiplesof same types so had to scan future indices. it became too unreadable yet worked, would love if someone else uses this logic of even odd poition and produces a better answer, but below is the logic I rested my head with.

 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    
	// created mapping of available bracket types
     const map = {
        '{': '}',
        '(': ')',
        '[': ']'
    }
	// checking if length is even, if not it is a fail from the start and no need to go further
    if(s.length%2 !== 0){
        return false;
    }
	// creating a buffer stack to push and pop items from 
    let balanceStack = [];
	
	//looping over the str
    for (let i = 0; i < s.length; i++) {
		// this basicaly unredable version of if(s[i] === '{' || s[i] === '(' ... so on )
		// am just getting all the keys from map object in an array and checking if and only if the char is an opening brace
        if(Object.keys(map).includes(s[i])) {
			// pushing the opening bracket in the stack
            balanceStack.push(s[i]);
        } else {
			// if it's a closing bracket then popping the opening bracket off of stack and tracking it with lastPopped
            let lastPopped = balanceStack.pop();
			
			// lastPopped should be a complement of closing bracket that is the current item and using map to determine that  
            if(map[lastPopped] !== s[i]){
                return false;
            }
        }
    }
	// at last checking if balanceStack array still have few items left then return false else we are good to go
    return (balanceStack.length>0)?false:true;  
       
};
Comments (0)