Quick actions

cmd+k|ctrl+k

Navigation

Languages

Parenthesis Reversal

Snippet info

Language

TypeScript

Visibility

public

Author

soham57

Created

2023-08-13T18:38:26.870903Z

Updated

2023-08-13T18:38:26.870903Z

function solution(inputString: string): string {
    let reversedStr = '';
    const stack: string[];

    for (let x = 0; x < inputString.length; x++) {
        console.log("Stack:", stack);
        console.log("rev: ",reversedStr)// Display the current stack
        if (inputString[x] === '(') {
            stack.push('');
        } else if (inputString[x] === ')') {
            let tempReverse = stack.pop()!.split('').reverse().join('');
            if (stack.length > 0) {
                stack[stack.length - 1] += tempReverse;
            } else {
                reversedStr += tempReverse;
            }
        } else if (stack.length > 0) {
            stack[stack.length - 1] += inputString[x];
        } else {
            reversedStr += inputString[x];
        }
    }
    console.log("Stack:", stack); // Display the final stack
    return reversedStr;
}

const inputStr = "(abc)d(efg)";
const reversed = solution(inputStr);
console.log(reversed);
INFO