Skip to content

Instantly share code, notes, and snippets.

@gabhi
Created April 7, 2015 09:37
Show Gist options
  • Select an option

  • Save gabhi/25a0994fd01f3a1d6795 to your computer and use it in GitHub Desktop.

Select an option

Save gabhi/25a0994fd01f3a1d6795 to your computer and use it in GitHub Desktop.
isValidParentheses
// 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