Skip to content

Commit d6b183a

Browse files
committed
Valid parentheses
1 parent 1a69c7b commit d6b183a

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ There might still be some personal comments added for my learning purposes.
4747
* Tree relation
4848
[`Solution`](https://github.com/edignot/algorithm-data-structure-practice/blob/master/src/recursion-tree/recursion-tree.js)
4949
[`Test file`](https://github.com/edignot/algorithm-data-structure-practice/blob/master/src/recursion-tree/recursion-tree.test.js)
50+
* Valid Parentheses
51+
[`Solution`](https://github.com/edignot/algorithm-data-structure-practice/blob/master/src/valid-parentheses/valid-parentheses.js)
52+
[`Test file`](https://github.com/edignot/algorithm-data-structure-practice/blob/master/src/valid-parentheses/valid-parentheses.test.js)
5053

5154
## Usage
5255
- Clone this repo
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Problem: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
2+
// An input string is valid if:
3+
// - Open brackets must be closed by the same type of brackets.
4+
// - Open brackets must be closed in the correct order.
5+
// https://leetcode.com/problems/valid-parentheses/
6+
// Time complexity:
7+
8+
const isValidParentheses = function (s) {
9+
if (s === "") return true;
10+
let index = -1;
11+
s.includes("()") && (index = s.indexOf("()"));
12+
s.includes("[]") && (index = s.indexOf("[]"));
13+
s.includes("{}") && (index = s.indexOf("{}"));
14+
if (index !== -1) {
15+
let arr = s.split("");
16+
arr.splice(index, 2);
17+
return isValidParentheses(arr.join(""));
18+
}
19+
return false;
20+
};
21+
22+
export default isValidParentheses;
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import isValidParentheses from "./valid-parentheses";
2+
3+
describe("Is input valid parenthesis", () => {
4+
test("Is input valid parenthesis", () => {
5+
expect(isValidParentheses("{}[]()")).toBe(true);
6+
});
7+
test("Is input valid parenthesis", () => {
8+
expect(isValidParentheses("[[{()}]]")).toBe(true);
9+
});
10+
test("Is input valid parenthesis", () => {
11+
expect(isValidParentheses("[[{({})")).toBe(false);
12+
});
13+
test("Is input valid parenthesis", () => {
14+
expect(isValidParentheses("[][]{}({})")).toBe(true);
15+
});
16+
test("Is input valid parenthesis", () => {
17+
expect(isValidParentheses("{something}")).toBe(false);
18+
});
19+
});

0 commit comments

Comments
 (0)