포스트

[Python] Programmers - pair removal

한국어 원문은 여기에서 볼 수 있습니다.
[Python] Programmers - pair removal

Programmers 짝지어 제거하기

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def solution(s):

    stack = []

    for ch in s:

        if stack and stack[-1] == ch:

            stack.pop()

        else:

            stack.append(ch)

    return 1 if not stack else 0
  • Insert one alphabet into the stack, bring in the next alphabet, and if it matches the previously inserted alphabet, pop the previously inserted alphabet. If it does not match, put that alphabet into the stack as well.
    • If you do this, if you succeed in pairing and removing all alphabets, the stack should be empty.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def solution(s):
    answer = -1
    arr = []

    while True:
        if len(arr) == len(s):
            return 1
        cnt = 1
        for i in range(0, len(s)-1):
            if s[i] == s[i+1]:
                arr.append(s[i])
                arr.append(s[i+1])
                if i+2 > len(s)-1 and i==0:
                    return 1
                elif i+2 > len(s)-1:
                    s = s[:i]
                elif i == 0:
                    s = s[i+2:]
                else:
                    s = s[:i] + s[i+2:]
                break
            else:
                cnt += 1
                if cnt == len(s):
                    return 0

    return answer

At first, I solved it as above, but the accuracy test timed out and the efficiency test failed.

The above problem must be solved using the stack.

  • I knew I had to use the stack, but I was wondering how to use it and ended up not using the stack.

  • It’s the same as just creating a new array and solving it.