Created
September 23, 2023 08:26
-
-
Save mohitsharma93/2b872c05cb29176948daca0bd1e0c876 to your computer and use it in GitHub Desktop.
question : Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’ determine if the input string is valid.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* question : Given a string s 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. | |
*/ | |
let parenthese = "()[]{}" | |
function checkByReplace(s) { | |
while(true) { | |
let len = s.length; | |
// Replace the string with '' one by one according to the matching pair | |
s = s.replace('()', '').replace('[]', '').replace('{}', ''); | |
/** | |
* two case when s.length equal to len | |
* 1. when all parentheses are matched and s become ''. | |
* 2. s cannot continue to match and its length is the same as the begining | |
* means ([) is length is 3 after replace it is still 3 so return false. | |
* in both case we have same length | |
*/ | |
if(s.length === len) { | |
return len === 0; | |
} | |
} | |
} | |
function checkByStack(s) { | |
if(!s) return true; // empty character string is valid. | |
const leftToRight = { | |
'(' : ')', | |
'{' : '}', | |
'[' : ']' | |
}; | |
const stack = []; | |
for(let i = 0, len = s.length; i < len; i++) { | |
const ch = s[i]; | |
// if left parentheses then push to stack. | |
if(leftToRight[ch]) { | |
stack.push(ch); | |
} else { | |
/** | |
* start to match parentheses | |
* if no left parentheses in stack means return false. | |
* if data but top element of stack is not the current colosing parentheses then return false. | |
*/ | |
if(!stack.length || (leftToRight[stack.pop()] !== ch)) { | |
return false; | |
} | |
} | |
} | |
return !stack.length; | |
} | |
console.time('checkByReplace'); | |
console.log('checkByReplace', checkByReplace(parenthese)); | |
console.timeEnd('checkByReplace'); | |
console.time('checkByStack'); | |
console.log('checkByStack', checkByStack(parenthese)) | |
console.timeEnd('checkByStack'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment