[CodeSignal]reverseInParentheses

bbolddagu·2023년 4월 20일
0

알고리즘

목록 보기
1/11

문제

Write a function that reverses characters in (possibly nested) parentheses in the input string.
Input strings will always be well-formed with matching ()s.

Example
For inputString = "(bar)", the output should be
solution(inputString) = "rab";
For inputString = "foo(bar)baz", the output should be
solution(inputString) = "foorabbaz";
For inputString = "foo(bar)baz(blim)", the output should be
solution(inputString) = "foorabbazmilb";
For inputString = "foo(bar(baz))blim", the output should be
solution(inputString) = "foobazrabblim".
Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim".
Input/Output

  • [execution time limit] 4 seconds (py3)

  • [input] string inputString

  • A string consisting of lowercase English letters and the characters ( and ). It is guaranteed that all parentheses in inputString form a regular bracket sequence.

  • Guaranteed constraints:
    0 ≤ inputString.length ≤ 50.

  • [output] string

  • Return inputString, with all the characters that were in parentheses reversed.

풀이

[나의 풀이]

from collections import deque

def solution(inputString):
    if len(inputString) <= 1: # 이 경우 빼먹지 말기
        return inputString
    
    input_list = list(inputString)
    n = len(input_list)
    
    q = deque([])
    q.append(input_list[0])
    idx = 1
    
    while q and idx < n:

        if input_list[idx] == ')':
            tmp = ''
            last = q.pop()
    
            while last != '(':
 
                tmp += last
                last = q.pop()
            # print(tmp)
            
            for i in tmp:
                q.append(i)
        
        else:
            q.append(input_list[idx])
            
        idx += 1
    
    ans = ''.join(q)
    return ans
    

[Best 풀이]

def solution(s):
    for i in range(len(s)):
        if s[i] == "(":
            start = i
        if s[i] == ")":
            end = i
            return solution(s[:start] + s[start+1:end][::-1] + s[end+1:])
    return s

0개의 댓글

Powered by GraphCDN, the GraphQL CDN