-
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.
- Loading branch information
Showing
3 changed files
with
52 additions
and
2 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
14 changes: 14 additions & 0 deletions
14
src/algorithms/stack/valid-parentheses/valid-parentheses.spec.ts
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,14 @@ | ||
import { isValid } from './valid-parentheses' | ||
|
||
describe('Valid parentheses', () => { | ||
it('is valid', () => { | ||
expect(isValid('()')).toBe(true) | ||
expect(isValid('()[]{}')).toBe(true) | ||
expect(isValid('{[]}')).toBe(true) | ||
}) | ||
|
||
it('is invalid', () => { | ||
expect(isValid('(]')).toBe(false) | ||
expect(isValid('([)]')).toBe(false) | ||
}) | ||
}) |
36 changes: 36 additions & 0 deletions
36
src/algorithms/stack/valid-parentheses/valid-parentheses.ts
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,36 @@ | ||
/** | ||
* Valid Parentheses | ||
* Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. | ||
An input string is valid if: | ||
1. Open brackets must be closed by the same type of brackets. | ||
2. Open brackets must be closed in the correct order. | ||
3. Every close bracket has a corresponding open bracket of the same type. | ||
Example 1: | ||
Input: s = "()" | ||
Output: true | ||
Example 2: | ||
Input: s = "()[]{}" | ||
Output: true | ||
* | ||
*/ | ||
export function isValid(s: string): boolean { | ||
const stack: string[] = [] | ||
|
||
for (const char of s) { | ||
if (char === '(') { | ||
stack.push(')') | ||
} else if (char === '[') { | ||
stack.push(']') | ||
} else if (char === '{') { | ||
stack.push('}') | ||
} else if (stack.pop() !== char) { | ||
return false | ||
} | ||
} | ||
|
||
return stack.length === 0 | ||
} |