From 80d5d72fe200d094dd8303ee20a4f28978bda364 Mon Sep 17 00:00:00 2001 From: SumeetHaryani Date: Sat, 5 Oct 2019 00:39:22 +0530 Subject: [PATCH] balanced-parenthesis --- README.md | 2 + .../Stack/balanced-parenthesis/index.js | 43 +++++++++++++++++++ src/_DataStructures_/Stack/index.js | 3 ++ 3 files changed, 48 insertions(+) create mode 100644 src/_DataStructures_/Stack/balanced-parenthesis/index.js diff --git a/README.md b/README.md index 3b441d03..c839b342 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct - [Implement Queue Using Stack](src/_DataStructures_/Stack/immitate-queue-using-stack) - [Baseball Game](src/_DataStructures_/Stack/baseball-game) - [Minimum Stack](src/_DataStructures_/Stack/min-stack) + - [Balanced Parenthesis](src/_DataStructures_/Stack/balanced-parenthesis) + - [Queue](src/_DataStructures_/Queue) - [Weave](src/_DataStructures_/Queue/weave) diff --git a/src/_DataStructures_/Stack/balanced-parenthesis/index.js b/src/_DataStructures_/Stack/balanced-parenthesis/index.js new file mode 100644 index 00000000..01b0c0cb --- /dev/null +++ b/src/_DataStructures_/Stack/balanced-parenthesis/index.js @@ -0,0 +1,43 @@ +/** + Given an expression string exp , write a program to examine whether the pairs and + the orders of "{","}","(",")","[","]" are correct in expression. + +Example: +Input: exp = "[()]{}{[()()]()}" +Output: true + +Input: exp = "[(])" +Output: false +*/ + + +const Stack = require('../index'); + +function checkBalancedParenthesis(expression) { + let s = new Stack(); + for (let i = 0; i < expression.length; i++) { + const char = expression[i]; + if (char === '{' || char === '(' || char === '[') { + //If current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack + s.push(char); + } else { + if (s.isEmpty()) { + //when we have only right parenthesis or brackets in expresion + return false; + } else if (char === '}' && s.peek() !== '{' || char === ')' && s.peek() !== '(' || char === ']' && s.peek() !== '[') { + return false; + } + //If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop it from stack + s.pop(); + } + } + if (s.isEmpty()) { + //expression has balanced parenthesis + return true; + } else { + return false; + } +} + +console.log(checkBalancedParenthesis("{()}[]")); //true +console.log(checkBalancedParenthesis("{()}}")); //false \ No newline at end of file diff --git a/src/_DataStructures_/Stack/index.js b/src/_DataStructures_/Stack/index.js index eb18a8ea..4836ae65 100644 --- a/src/_DataStructures_/Stack/index.js +++ b/src/_DataStructures_/Stack/index.js @@ -15,6 +15,9 @@ class Stack { peek() { return this.data[this.data.length - 1]; } + isEmpty(){ //check if stack is empty + return this.data.length==0; + } } module.exports = Stack;

AltStyle によって変換されたページ (->オリジナル) /