Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Dec 19, 2023. It is now read-only.

Commit 4ce94dc

Browse files
committed
Add problem 541
1 parent 55b6dac commit 4ce94dc

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

‎algorithms/541/README.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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]

‎algorithms/541/solution.go‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /