Problem
Solution
Initial thoughts
Python implementation
1 2 3 4 5 6 7 8 9 10 11
|
class : def reverseStr(self, s, k): """ :type s: str :type k: int :rtype: str """ lst = list(s) for s in range(0, len(s), 2*k): lst[s:s+k] = lst[s:s+k][::-1] return "".join(lst)
|
Java implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class { public String reverseStr(String s, int k) { char[] lst = s.toCharArray(); for(int st = 0; st < lst.length; st += 2*k){ int i = st; int j = (st+k-1 < lst.length) ? (st+k-1) : (lst.length-1); while(i < j){ char temp = lst[j]; lst[j] = lst[i]; lst[i] = temp; i++; j--; } } return new String(lst); } }
|
Time complexity
O(n).
Space complexity
O(n).
Links
541. Reverse String II
(中文版) 算法笔记: 力扣#541 反转字符串 II
近期评论