[JS+Python/HackerRank] Super Reduced String

정나린·2023년 4월 3일
0

💬 문제

문제 난이도: Easy

문제 링크: https://www.hackerrank.com/challenges/reduced-string/problem?isFullScreen=true

문제 설명

주어진 문자열에서 인접한 두 문자를 삭제하는 연산을 반복하고, 그 결과를 리턴하라.

코드(Python)

def superReducedString(s):
    arr = list(s)
    stack = [arr.pop()]
    while arr:
        if stack and arr[-1] == stack[-1]:
            arr.pop()
            stack.pop()
        else:
            stack.append(arr.pop())
    if not stack:
        return 'Empty String'
    else:
        stack.reverse()
        return ''.join(stack)

코드(Javascript)

function superReducedString(s) {
    const arr = s.split('');
    const stack = [arr.pop()];

    while (arr.length){
        const elem = arr.pop();
        if (stack.length){
            if (elem === stack[stack.length -1]){
                stack.pop();
            }else{
                stack.push(elem)
            }
        }else{
            stack.push(elem);
        }
    }
    return (stack.length) ? stack.reverse().join('') : 'Empty String'
    
}

0개의 댓글