File tree Expand file tree Collapse file tree 2 files changed +62
-0
lines changed
src/algorithms/parentheses Expand file tree Collapse file tree 2 files changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ /* es un evaluador de cadenas de parentesis */
2+ /* recibe un string con parentesis y si los parentesis cierran correctamente devuelve true, como un analizador sintactico */
3+
4+ // isValidParentheses("()") // Output: true
5+ // isValidParentheses("()[]{}") // Output: true
6+ // isValidParentheses("(]") // Output: false
7+ // isValidParentheses("([)]") // Output: false
8+ // isValidParentheses("{[]}") // Output: true
9+ // isValidParentheses("[") // Output: false
10+
11+ export const isValidParentheses = ( str : string ) => {
12+ const stack = [ ] ;
13+
14+ // Creamos un mapa para mapear paréntesis de apertura a cierre
15+ const map = {
16+ '(' : ')' ,
17+ '[' : ']' ,
18+ '{' : '}' ,
19+ } ;
20+
21+ // Recorremos cada carácter en la cadena de entrada
22+ for ( const char of str ) {
23+ // Si el carácter es un paréntesis de apertura, lo agregamos a la pila
24+ if ( map [ char ] ) {
25+ stack . push ( char ) ;
26+ } else {
27+ // Si el carácter es un paréntesis de cierre
28+ // verificamos si la pila está vacía o si el último paréntesis abierto no coincide
29+ if ( stack . length === 0 || map [ stack . pop ( ) ] !== char ) {
30+ return false ; // No coinciden los paréntesis
31+ }
32+ }
33+ }
34+
35+ // Si la pila está vacía al final, todos los paréntesis se cerraron correctamente
36+ return stack . length === 0 ;
37+ } ;
Original file line number Diff line number Diff line change 1+ import { describe , test } from 'vitest' ;
2+
3+ import { isValidParentheses } from '../parentheses' ;
4+
5+ describe ( 'Parentheses' , ( ) => {
6+ test ( 'isValidParentheses function is defined' , ( ) => {
7+ expect ( typeof isValidParentheses ) . toEqual ( 'function' ) ;
8+ } ) ;
9+
10+ test ( '"()" is a valid parentheses' , ( ) => {
11+ expect ( isValidParentheses ( '()' ) ) . toBeTruthy ( ) ;
12+ } ) ;
13+
14+ test ( '"([)]" is not a valid parentheses' , ( ) => {
15+ expect ( isValidParentheses ( '([)]' ) ) . toBeFalsy ( ) ;
16+ } ) ;
17+
18+ test ( '"[" is not a valid parentheses' , ( ) => {
19+ expect ( isValidParentheses ( '[' ) ) . toBeFalsy ( ) ;
20+ } ) ;
21+
22+ test ( '"()[]{}" is a valid parentheses' , ( ) => {
23+ expect ( isValidParentheses ( '()[]{}' ) ) . toBeTruthy ( ) ;
24+ } ) ;
25+ } ) ;
You can’t perform that action at this time.
0 commit comments