Letcode541: 문자열 반전 II(문자열)

1301 단어 Leetcode
제목 설명:
코드:
1. 2k주기로 순차적으로 뒤집기, 운행시간 72ms
class Solution:
    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        if(k==1 or len(s)<=3):
            return s
        elif(len(s)<=k):
            return s[::-1]
        elif(len(s)<=2*k):
            return s[0:k][::-1]+s[k:len(s)]
        else:
            i=0
            strout=''
            while(i<=len(s)-len(s)%(2*k)-2*k):
                strout+=s[i:i+k][::-1]+s[i+k:i+2*k]
                i+=2*k
            if(len(s)%(2*k)>=k):
                j=len(s)-len(s)%(2*k)
                strout+=s[j:j+k][::-1]+s[j+k:len(s)]
            else:
                strout+=s[len(s)-len(s)%(2*k):len(s)][::-1]
            return strout
 

2 list 목록을 이용하여 52ms를 사용하여 개선했습니다
class Solution:
    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        stack=[]
        while s:
            stack.append(s[:k])
            s=s[k:]
        #print(stack)
        for i in range(len(stack)):
            if (i+1)%2!=0:
                stack[i]=stack[i][::-1]
        return ''.join(stack)

좋은 웹페이지 즐겨찾기