Skip to content

Commit

Permalink
add solution for valid parenthese
Browse files Browse the repository at this point in the history
  • Loading branch information
ragmha committed May 4, 2024
1 parent 3103053 commit eca7682
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 2 deletions.
4 changes: 2 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
## Algorithms (18/ 167)
## Algorithms (19/ 167)

| Name | Tags | Solution |
| --------------------------------------------------------- | ----------------------- | ----------------------------------------------------------------------- |
Expand Down Expand Up @@ -32,7 +32,7 @@
| 3Sum | `Two Pointers` |   |
| Container With Most Water | `Two Pointers` |   |
| Trapping Rain Water | `Two Pointers` |   |
| Valid Parentheses | `Stack` |   |
| Valid Parentheses | `Stack` | [Typescript]('./src/algorithms/stack/valid-parentheses') |
| Min Stack | `Stack` |   |
| Evaluate Reverse Polish Notation | `Stack` |   |
| Generate Parentheses | `Stack` |   |
Expand Down
14 changes: 14 additions & 0 deletions src/algorithms/stack/valid-parentheses/valid-parentheses.spec.ts
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 src/algorithms/stack/valid-parentheses/valid-parentheses.ts
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
}

0 comments on commit eca7682

Please sign in to comment.