LeetCode Solutions

541. Reverse String II

Time: $O(|\texttt{s}|k)$

Space: $O(1)$

			

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;
  }
};
			

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();
  }
}
			

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 ""