중앙백 2021. 12. 21. 15:54

Programmers Level.2 괄호 변환

def divide(p):
    cnt = 0
    u = ''
    is_balanced = True # u가 올바른 문자열인가?
    for i in range(len(p)):
        if p[i] == '(':
            cnt += 1
        else:
            cnt -= 1
        u += p[i]
        if cnt < 0: # 한 번이라도 0보다 작아지면 올바른 문자열이 아니다.
            is_balanced = False
        if cnt == 0: # 균형잡힌 문자열이면 반복문 끝.
            v = p[i+1:]
            break
    return u, v, is_balanced # 두 개의 문자열 반환


def change(p): # 첫 번째 마지막 문자 제거 후 괄호 방향 뒤집어 붙이기
    p = p[1:-1]
    q = ''
    for i in p:
        if i == '(':
            q += ')'
        else:
            q += '('
    return q
    

def solution(p):
    if p == '':
        return ''
    u, v, is_balanced = divide(p)
    if is_balanced:
        answer = u + solution(v)
    else:
        answer = '(' + solution(v) + ')' + change(u)
    return answer

 - 문제가 길고 복잡해서 처음에는 막막했는데, 1번 조건부터 하나씩 구현하니까 생각보다 어렵지 않았다.

 - 다른 사람의 풀이는 join과 람다식을 이용해서 좀 더 간단히 구현했다.

def solution(p):
    if p=='': return p
    r=True; c=0
    for i in range(len(p)):
        if p[i]=='(': c-=1
        else: c+=1
        if c>0: r=False
        if c==0:
            if r:
                return p[:i+1]+solution(p[i+1:])
            else:
                return '('+solution(p[i+1:])+')'+''.join(list(map(lambda x:'(' if x==')' else ')',p[1:i]) ))

 

 

Programmers Level.2 거리두기 확인하기

def check(row, column, place):
    way1 = [(0,1),(1,0),(-1,0),(0,-1)]
    way2 = [(0,2),(2,0),(0,-2),(-2,0)]
    way3 = [(1,1),(1,-1),(-1,-1),(-1,1)]
    for dx, dy in way1:
        nx = row + dx
        ny = column + dy
        if nx< 0 or ny<0 or nx>4 or ny>4:
            continue
        if place[nx][ny] == 'P':
            return 0
    for dx, dy in way2:
        nx = row + dx
        ny = column + dy
        if nx< 0 or ny<0 or nx>4 or ny>4:
            continue
        if place[nx][ny] == 'P' and place[row+ dx//2][column + dy//2] != 'X':
            return 0
    for dx, dy in way3:
        nx = row + dx
        ny = column + dy
        if nx< 0 or ny<0 or nx>4 or ny>4:
            continue
        if place[nx][ny] == 'P' and (place[nx][column] != 'X' or place[row][ny] != 'X'):
            return 0
    return 1


def solution(places):
    answer = []
    for place in places:
        cnt = 1
        for row in range(5):
            for column in range(5):
                if place[row][column] == 'P':
                    cnt *= check(row, column, place)
        if cnt == 1:
            answer.append(1)
        else:
            answer.append(0)
    return answer

 - 5X5 array를 5개만 확인해봐도 되서 완전탐색을 활용했다. 모든 점에 대해서 'P'라는 값을 가지면 check함수에 넣어 상하좌우를 각각 확인하고 조건을 만족하는지를 확인했다.

 - 아래는 다른 사람의 풀이인데, 비슷하게 했지만 좀 더 나은 풀이라고 생각하는 점은, irow + 1인 경우만 살펴보게 했다는 것. 내 풀이에서는 irow - 1도 살펴보게 했고 굳이 그럴 필요가 없었던 것.

def check(place):
    for irow, row in enumerate(place):
        for icol, cell in enumerate(row):
            if cell != 'P':
                continue
            if irow != 4 and place[irow + 1][icol] == 'P':
                return 0
            if icol != 4 and place[irow][icol + 1] == 'P':
                return 0
            if irow < 3 and place[irow + 2][icol] == 'P' and place[irow + 1][icol] != 'X':
                return 0
            if icol < 3 and place[irow][icol + 2] == 'P' and place[irow][icol + 1] != 'X':
                return 0
            if irow != 4 and icol != 4 and place[irow + 1][icol + 1] == 'P' and (place[irow + 1][icol] != 'X' or place[irow][icol + 1] != 'X'):
                return 0
            if irow != 4 and icol != 0 and place[irow + 1][icol - 1] == 'P' and (place[irow + 1][icol] != 'X' or place[irow][icol - 1] != 'X'):
                return 0
    return 1

def solution(places):
    return [check(place) for place in places]