Created
April 7, 2015 09:37
-
-
Save gabhi/25a0994fd01f3a1d6795 to your computer and use it in GitHub Desktop.
isValidParentheses
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
| // Time complexity: O(n) | |
| function isValidParentheses(str) { | |
| var i = 0, l = str.length, arr = []; | |
| if (!l) { | |
| return true; | |
| } | |
| if ((l % 2) !== 0) { | |
| return false; | |
| } | |
| while (i < l) { | |
| var s = str[i]; | |
| if (s == "{") { | |
| arr.push(s); | |
| } else if (s == "}") { | |
| if (arr.length) { | |
| arr.pop(); | |
| } else { | |
| return false; | |
| } | |
| } | |
| i++; | |
| } | |
| return true; | |
| } | |
| isValidParentheses("{{{}}}"); // true | |
| isValidParentheses("{{}{}}"); // true | |
| isValidParentheses("{}{{}}"); // true | |
| isValidParentheses("}{}{"); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment