Valid Parentheses
Easy stack · strings
Description
Constraints
0 <= length <= 100000; characters are ()[]{}
Examples
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false
Hints (1)
- Push openers; on a closer, the top of the stack must match.
Solutions
Stack of open brackets. · Time O(n) · Space O(n)
func isValid(s string) bool {
pairs := map[rune]rune{')': '(', ']': '[', '}': '{'}
var stack []rune
for _, c := range s {
if open, ok := pairs[c]; ok {
if len(stack) == 0 || stack[len(stack)-1] != open {
return false
}
stack = stack[:len(stack)-1]
} else {
stack = append(stack, c)
}
}
return len(stack) == 0
}
Stack of open brackets. · Time O(n) · Space O(n)
function isValid(s) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of s) {
if (pairs[c]) { if (stack.pop() !== pairs[c]) return false; }
else stack.push(c);
}
return stack.length === 0;
}
Stack of open brackets. · Time O(n) · Space O(n)
function isValid($s) {
$pairs = [')' => '(', ']' => '[', '}' => '{'];
$stack = [];
for ($i = 0; $i < strlen($s); $i++) {
$c = $s[$i];
if (isset($pairs[$c])) {
if (array_pop($stack) !== $pairs[$c]) { return false; }
} else {
$stack[] = $c;
}
}
return $stack === [];
}
Stack of open brackets. · Time O(n) · Space O(n)
def isValid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for c in s:
if c in pairs:
if not stack or stack.pop() != pairs[c]:
return False
else:
stack.append(c)
return not stack
Stack of open brackets. · Time O(n) · Space O(n)
function isValid(s: string): boolean {
const pairs: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
const stack: string[] = [];
for (const c of s) {
if (pairs[c]) { if (stack.pop() !== pairs[c]) return false; }
else stack.push(c);
}
return stack.length === 0;
}
Create a free account to submit solutions, track progress and save problems.
Create account