Skip to content

Instantly share code, notes, and snippets.

@farkwun
Created August 20, 2017 07:26
Show Gist options
  • Save farkwun/f496d779355521ce55acdd41c4e64b50 to your computer and use it in GitHub Desktop.
Save farkwun/f496d779355521ce55acdd41c4e64b50 to your computer and use it in GitHub Desktop.
541. Reverse String II
# https://leetcode.com/problems/reverse-string-ii/description/
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
half_k = k//2
str_ptr = 0
s_list = list(s)
while str_ptr < len(s):
temp_head = str_ptr
temp_tail = str_ptr + k - 1
if temp_tail >= len(s):
temp_tail = len(s) - 1
while temp_head < temp_tail:
s_list[temp_head], s_list[temp_tail] = s_list[temp_tail], s_list[temp_head]
temp_head += 1
temp_tail -= 1
str_ptr += (2 * k)
return ''.join(s_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment