Skip to content

Commit 661da72

Browse files
committed
feat(js): add modular solution and documentation for normal challenge 7 - Validate Parentheses
1 parent 8de48f2 commit 661da72

File tree

3 files changed

+139
-0
lines changed

3 files changed

+139
-0
lines changed
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Create a function that, given a string composed of parentheses and possibly other opening and closing symbols, verifies if the sequence is valid (i.e., each open symbol has its corresponding closing symbol in the correct order). Use a stack data structure to solve it.
7+
8+
### Code Explanation
9+
The solution uses a stack to track opening symbols. For each character:
10+
- If it is an opening symbol, push it onto the stack.
11+
- If it is a closing symbol, check if the top of the stack matches the corresponding opening symbol.
12+
- If not, the sequence is invalid.
13+
- Ignore other characters.
14+
15+
The sequence is valid if the stack is empty at the end.
16+
17+
### Relevant Code Snippet
18+
19+
```javascript
20+
function isValidParentheses(s) {
21+
const stack = [];
22+
const mapping = { ')': '(', ']': '[', '}': '{' };
23+
24+
for (const char of s) {
25+
if (Object.values(mapping).includes(char)) {
26+
stack.push(char);
27+
} else if (char in mapping) {
28+
if (stack.length === 0 || stack.pop() !== mapping[char]) {
29+
return false;
30+
}
31+
} else {
32+
// Ignore other characters
33+
continue;
34+
}
35+
}
36+
37+
return stack.length === 0;
38+
}
39+
```
40+
41+
### Example Usage
42+
43+
```javascript
44+
import isValidParentheses from './parentheses.js';
45+
46+
const testStrings = ["()", "()[]{}", "(]", "([)]", "{[]}"];
47+
testStrings.forEach(s => {
48+
console.log(`Is '${s}' valid?`, isValidParentheses(s));
49+
});
50+
```
51+
52+
---
53+
54+
## Versión en Español
55+
56+
### Descripción del Reto
57+
Crea una función que, dada una cadena compuesta por paréntesis y posiblemente otros símbolos de apertura y cierre, verifique si la secuencia es válida (es decir, que cada símbolo de apertura tenga su correspondiente símbolo de cierre en el orden correcto). Usa una estructura de datos pila para resolverlo.
58+
59+
### Explicación del Código
60+
La solución usa una pila para rastrear los símbolos de apertura. Para cada carácter:
61+
- Si es un símbolo de apertura, se agrega a la pila.
62+
- Si es un símbolo de cierre, se verifica si el tope de la pila coincide con el símbolo de apertura correspondiente.
63+
- Si no, la secuencia es inválida.
64+
- Se ignoran otros caracteres.
65+
66+
La secuencia es válida si la pila está vacía al final.
67+
68+
### Fragmento de Código Relevante
69+
70+
```javascript
71+
function isValidParentheses(s) {
72+
const stack = [];
73+
const mapping = { ')': '(', ']': '[', '}': '{' };
74+
75+
for (const char of s) {
76+
if (Object.values(mapping).includes(char)) {
77+
stack.push(char);
78+
} else if (char in mapping) {
79+
if (stack.length === 0 || stack.pop() !== mapping[char]) {
80+
return false;
81+
}
82+
} else {
83+
// Ignorar otros caracteres
84+
continue;
85+
}
86+
}
87+
88+
return stack.length === 0;
89+
}
90+
```
91+
92+
### Ejemplo de Uso
93+
94+
```javascript
95+
import isValidParentheses from './parentheses.js';
96+
97+
const testStrings = ["()", "()[]{}", "(]", "([)]", "{[]}"];
98+
testStrings.forEach(s => {
99+
console.log(`¿Es '${s}' válido?`, isValidParentheses(s));
100+
});
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// main.js - Example usage of isValidParentheses function
2+
3+
import isValidParentheses from './parentheses.js';
4+
5+
/*
6+
Challenge: Create a function that, given a string composed of parentheses and possibly other opening and closing symbols, verifies if the sequence is valid (i.e., each open symbol has its corresponding closing symbol in the correct order). Use a stack data structure to solve it.
7+
*/
8+
9+
function main() {
10+
const testStrings = ["()", "()[]{}", "(]", "([)]", "{[]}"];
11+
testStrings.forEach(s => {
12+
console.log(`Is '${s}' valid?`, isValidParentheses(s));
13+
});
14+
}
15+
16+
main();
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// parentheses.js - Validate parentheses and other symbols using a stack
2+
3+
function isValidParentheses(s) {
4+
const stack = [];
5+
const mapping = { ')': '(', ']': '[', '}': '{' };
6+
7+
for (const char of s) {
8+
if (Object.values(mapping).includes(char)) {
9+
stack.push(char);
10+
} else if (char in mapping) {
11+
if (stack.length === 0 || stack.pop() !== mapping[char]) {
12+
return false;
13+
}
14+
} else {
15+
// Ignore other characters
16+
continue;
17+
}
18+
}
19+
20+
return stack.length === 0;
21+
}
22+
23+
export default isValidParentheses;

0 commit comments

Comments
 (0)