-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add solution for valid-parentheses problem
- Loading branch information
1 parent
673066c
commit 8159530
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
// Problem: https://leetcode.com/problems/valid-parentheses/ | ||
// Doc: https://leetcode.com/problems/valid-parentheses/solutions/5491623/efficient-solution-for-valid-parentheses/ | ||
const isValid = (s: string): boolean => { | ||
const stack: string[] = []; | ||
|
||
const parClosedMap = { | ||
')': '(', | ||
'}': '{', | ||
']': '[', | ||
}; | ||
|
||
for (let i = 0; i < s.length; i++) { | ||
const char = s[i]; | ||
if (!(char in parClosedMap)) { | ||
stack.push(char); | ||
continue; | ||
} | ||
|
||
const popped = stack.pop(); | ||
if (!popped) return false; | ||
const opened = parClosedMap[char]; | ||
if (popped !== opened) return false; | ||
} | ||
|
||
return stack.length === 0; | ||
}; | ||
|
||
describe('Valid Parentheses', () => { | ||
it('should return true for valid parentheses', () => { | ||
expect(isValid('()')).toBe(true); | ||
expect(isValid('()[]{}')).toBe(true); | ||
expect(isValid('{[]}')).toBe(true); | ||
expect(isValid('([{}])')).toBe(true); | ||
}); | ||
|
||
it('should return false for invalid parentheses', () => { | ||
expect(isValid('(]')).toBe(false); | ||
expect(isValid('([)]')).toBe(false); | ||
expect(isValid('[')).toBe(false); | ||
expect(isValid(']')).toBe(false); | ||
}); | ||
}); |