Algorithm/python tip

942. DI String Match

개구리는 개꿀개꿀 2021. 2. 27. 03:57

leetcode.com/problems/di-string-match/

 

DI String Match - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

'''
I와 D로 구성된 문자열 S가 있다, N = S.length
다음을 만족하는 길이 N + 1 인 어떤 순열 A를 리턴하라.
S[i] == I : A[i] < A[i+1]
S[i] == D : A[i] > A[i+1]

solution)
    [0, 1, 2, 3, 4, .. N] 리스트를 만든다
    S를 순서대로 읽으면서 I이면 앞에서, D이면 뒤에서 뽑아서 순서대로 넣는다.
'''

class Solution(object):
    def diStringMatch(self, S):
        temp = list(range(0, len(S) + 1))
        ans = []
        start = 0
        end = len(S)
        for c in S:
            if c == 'I':
                ans.append(temp[start])
                start += 1
            else:
                ans.append(temp[end])
                end -= 1
        ans.append(temp[end])
        return ans
        

better answer

- a.pop(0) : a의 첫번째 요소를 반환

- a.pop(-1): a의 마지막 요소를 반환

leedakyeong.tistory.com/entry/python-for%EB%AC%B8-if%EB%AC%B8-%ED%95%9C-%EC%A4%84%EB%A1%9C-%EC%BD%94%EB%94%A9%ED%95%98%EA%B8%B0

class Solution(object):
    def diStringMatch(self, S):
        a = [s for s in range(len(S)+1)]
        return [a.pop(0) if i == "I" else a.pop(-1)  for i in S] + a