Skip to content

541. Reverse String II 👎

  • Time: $O(|\texttt{s}|k)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  string reverseStr(string s, int k) {
    for (size_t i = 0; i < s.length(); i += 2 * k) {
      int l = i;
      int r = min(i + k - 1, s.length() - 1);
      while (l < r)
        swap(s[l++], s[r--]);
    }

    return s;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public String reverseStr(String s, int k) {
    StringBuilder sb = new StringBuilder(s);

    for (int i = 0; i < sb.length(); i += 2 * k) {
      int l = i;
      int r = Math.min(i + k - 1, sb.length() - 1);
      while (l < r) {
        sb.setCharAt(l, s.charAt(r));
        sb.setCharAt(r, s.charAt(l));
        ++l;
        --r;
      }
    }

    return sb.toString();
  }
}
1
2
3
class Solution:
  def reverseStr(self, s: str, k: int) -> str:
    return s[:k][::-1] + s[k:2 * k] + self.reverseStr(s[2 * k:], k) if s else ""