This repository was archived by the owner on Dec 19, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ ## 541. Reverse String II
2+
3+ Given a string and an integer k, you need to reverse the first k characters for every 2k
4+ characters counting from the start of the string. If there are less than k characters
5+ left, reverse all of them. If there are less than 2k but greater than or equal to k
6+ characters, then reverse the first k characters and left the other as original.
7+
8+ ** Example:**
9+ <pre >
10+ <b >Input:</b > s = abcdefg, k = 2
11+ <b >Output:</b > bacdfeg
12+ </pre >
13+
14+ ** Restrictions:**
15+
16+ 1 . The string consists of lower English letters only.
17+ 2 . Length of the given string and k will in the range [ 1, 10000]
Original file line number Diff line number Diff line change 1+ package main
2+
3+ import "strings"
4+
5+ // Time and space complexity, O(n) where n is length of the string
6+ func reverseStr (s string , k int ) string {
7+ var sb strings.Builder
8+ l := len (s )
9+ for i := 0 ; i < l ; {
10+ if l < i + k {
11+ k = l - i
12+ }
13+ for j := i + k - 1 ; i <= j ; j -- {
14+ sb .WriteByte (s [j ])
15+ }
16+ e := i + 2 * k
17+ if l < e {
18+ e = l
19+ }
20+ sb .WriteString (s [i + k : e ])
21+ i = e
22+ }
23+ return sb .String ()
24+ }
You can’t perform that action at this time.
0 commit comments