diff --git a/leetcode/501-600/0541.Reverse-String-II/README.md b/leetcode/501-600/0541.Reverse-String-II/README.md index 4b1247da7..9c90b1490 100644 --- a/leetcode/501-600/0541.Reverse-String-II/README.md +++ b/leetcode/501-600/0541.Reverse-String-II/README.md @@ -1,28 +1,23 @@ # [541.Reverse String II][title] -> [!WARNING|style:flat] -> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm) - ## Description +Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. + +If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: s = "abcdefg", k = 2 +Output: "bacdfeg" ``` -## 题意 -> ... - -## 题解 +**Example 2:** -### 思路1 -> ... -Reverse String II -```go ``` - +Input: s = "abcd", k = 2 +Output: "bacd" +``` ## 结语 diff --git a/leetcode/501-600/0541.Reverse-String-II/Solution.go b/leetcode/501-600/0541.Reverse-String-II/Solution.go index d115ccf5e..9cc7289cf 100644 --- a/leetcode/501-600/0541.Reverse-String-II/Solution.go +++ b/leetcode/501-600/0541.Reverse-String-II/Solution.go @@ -1,5 +1,14 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(s string, k int) string { + bs := []byte(s) + start := 0 + for start < len(s) { + nextStart := start + 2*k + for s, e := start, min(start+k-1, len(s)-1); s < e; s, e = s+1, e-1 { + bs[s], bs[e] = bs[e], bs[s] + } + start = nextStart + } + return string(bs) } diff --git a/leetcode/501-600/0541.Reverse-String-II/Solution_test.go b/leetcode/501-600/0541.Reverse-String-II/Solution_test.go index 14ff50eb4..69157068b 100644 --- a/leetcode/501-600/0541.Reverse-String-II/Solution_test.go +++ b/leetcode/501-600/0541.Reverse-String-II/Solution_test.go @@ -10,30 +10,30 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + str string + k int + expect string }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", "abcdefg", 2, "bacdfeg"}, + {"TestCase2", "abcd", 2, "bacd"}, } // 开始测试 for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { - got := Solution(c.inputs) + got := Solution(c.str, c.k) if !reflect.DeepEqual(got, c.expect) { - t.Fatalf("expected: %v, but got: %v, with inputs: %v", - c.expect, got, c.inputs) + t.Fatalf("expected: %v, but got: %v, with inputs: %v %v", + c.expect, got, c.str, c.k) } }) } } -// 压力测试 +// 压力测试 func BenchmarkSolution(b *testing.B) { } -// 使用案列 +// 使用案列 func ExampleSolution() { }