C# in place O(n) solution


  • 0
    N
    public class Solution {
        public string ReverseStr(string s, int k) {
            
            char[] arr = s.ToCharArray();
            int n = arr.Length;
            int i = 0;
            while(i < n) {
                int j = Math.Min(i + k - 1, n - 1);
                swap(arr, i, j);
                i = i + 2 * k;
            }
            return new string(arr);
        }
        
        private void swap(char[] arr, int l, int r) {
            while (l < r) {
                char temp = arr[l];
                arr[l++] = arr[r];
                arr[r--] = temp;
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.