返回介绍

solution / 0500-0599 / 0541.Reverse String II / README_EN

发布于 2024-06-17 01:03:59 字数 2665 浏览 0 评论 0 收藏 0

541. Reverse String II

中文文档

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: s = "abcdefg", k = 2
Output: "bacdfeg"

Example 2:

Input: s = "abcd", k = 2
Output: "bacd"

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of only lowercase English letters.
  • 1 <= k <= 104

Solutions

Solution 1

class Solution:
  def reverseStr(self, s: str, k: int) -> str:
    t = list(s)
    for i in range(0, len(t), k << 1):
      t[i : i + k] = reversed(t[i : i + k])
    return ''.join(t)
class Solution {
  public String reverseStr(String s, int k) {
    char[] chars = s.toCharArray();
    for (int i = 0; i < chars.length; i += (k << 1)) {
      for (int st = i, ed = Math.min(chars.length - 1, i + k - 1); st < ed; ++st, --ed) {
        char t = chars[st];
        chars[st] = chars[ed];
        chars[ed] = t;
      }
    }
    return new String(chars);
  }
}
class Solution {
public:
  string reverseStr(string s, int k) {
    for (int i = 0, n = s.size(); i < n; i += (k << 1)) {
      reverse(s.begin() + i, s.begin() + min(i + k, n));
    }
    return s;
  }
};
func reverseStr(s string, k int) string {
  t := []byte(s)
  for i := 0; i < len(t); i += (k << 1) {
    for st, ed := i, min(i+k-1, len(t)-1); st < ed; st, ed = st+1, ed-1 {
      t[st], t[ed] = t[ed], t[st]
    }
  }
  return string(t)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文