C# - O(n/k) solution


  • 0
    K
            public string ReverseStr_Better(string s, int k)
            {
                // Catch error conditions
                if (string.IsNullOrEmpty(s) || k < 2) return s;
    
                char[] a = s.ToCharArray();
    
                for(int n = 0; n < s.Length; n += 2*k)
                {
                    // Determine where the current reverse should end: either (a) after transversing k characters or (b) coming to the end of the string (whichever is smaller)
                    int m = Math.Min(n + k, s.Length);
                    
                    // Inner-loop performs the actual reversing of the characters
                    for(int j = n; j < m; j++)
                    {
                        // Calculate position of character within group e.g. first character is pos 0, second pos 1 ...
                        int pos = j - n;
    
                        // Calculate the position of the new character, which is simply at the end of the group - pos
                        int newPos = m - pos - 1;
    
                        // Place the character in the new position
                        a[newPos] = s[j];
                    }
                }
    
                return new string(a);
            }
    

Log in to reply
 

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