Created
February 25, 2017 06:20
-
-
Save paolaozv/ca2363c2c6e2e8cd6d2b6fba2e251d1d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| function Stack(){ | |
| this.items = []; | |
| this.elements = 0; | |
| this.push = push; | |
| this.pop = pop; | |
| this.isEmpty = isEmpty; | |
| this.peek = peek; | |
| this.size = size; | |
| function push( item ){ | |
| this.items.push( item ); | |
| this.elements++; | |
| } | |
| function pop(){ | |
| if ( this.elements > 0 ) | |
| { | |
| this.elements--; | |
| return this.items.pop(); | |
| } | |
| } | |
| function peek(){ | |
| return this.items[ this.elements - 1 ]; | |
| } | |
| function isEmpty(){ | |
| return this.elements == 0; | |
| } | |
| function size(){ | |
| return this.elements; | |
| } | |
| } | |
| function balanced( s ){ | |
| var st = new Stack(); | |
| for (var i = 0; i < s.length; i++) { | |
| if(s[i] == ")" || s[i] == "]") | |
| { | |
| if(st.isEmpty()) | |
| return false; | |
| else | |
| { | |
| if(s[i] == ")" && st.peek() == "(" ) | |
| st.pop(); | |
| else if(s[i] == "]" && st.peek() == "[" ) | |
| st.pop(); | |
| else | |
| return false; | |
| } | |
| } | |
| else | |
| { | |
| if(s[i] == "(" || s[i] == "[") | |
| st.push(s[i]); | |
| } | |
| } | |
| if(st.isEmpty()) | |
| return true; | |
| else | |
| return false; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment