Skip to content

Latest commit

 

History

History
45 lines (34 loc) · 878 Bytes

541. Reverse String II.md

File metadata and controls

45 lines (34 loc) · 878 Bytes

Solution

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
    
        n=len(s)
        q=n//(2*k)
        start=0
        res=''

        for i in range(q+1):
            start=i*(2*k)
            end=(i+1)*(2*k)

            temp=s[start:end]                         #remember

            if len(temp)<k:
                temp=temp[::-1]
            else:
                temp=temp[0:k][::-1] + temp[k:]       #mistake prone
            res=res+temp

        return res

Improvisation

Using step in range(i, f, k)

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
		
        res=''
        for i in range(0, len(s), 2*k):
            word=s[i:i+2*k]
            if len(word)<k:
                word=word[::-1]
            else:
                word=word[0:k][::-1]+word[k:]
		
            res=res+word
	
        return res