C# Bit more efficient - Copy and Reverse in Single Pass


  • 0
    S
    public string ReverseStr(string srcStr, int k)
    {
        if (string.IsNullOrWhiteSpace(srcStr))
            return srcStr;
    
        int frwdIndx = 0;
        int bkwdIndx = 0;
    
        char[] chars = new char[srcStr.Length];
        int kPosIndx = Math.Min(k - 1, srcStr.Length - 1);
    
        while (frwdIndx < srcStr.Length)
        {
            for (bkwdIndx = kPosIndx; frwdIndx <= kPosIndx; bkwdIndx--)
            {
                chars[frwdIndx] = srcStr[bkwdIndx];
                frwdIndx++;
            }
    
            kPosIndx = Math.Min(kPosIndx + k, srcStr.Length - 1);
    
            while (frwdIndx <= kPosIndx)
            {
                chars[frwdIndx] = srcStr[frwdIndx];
                frwdIndx++;
            }
    
            kPosIndx = Math.Min(kPosIndx + k, srcStr.Length - 1);
        }
    
        return new string(chars);
    }
    

Log in to reply
 

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