C# solution and comments


  • 1
    B
    public class Solution {
    	public string ReverseStr(string s, int k)
    	{
    		// Initializing array of string pieces to reverse
    		IList<string> reversed = new List<string>();
    		int subset;
    
    		// Assigning stepsize for number of subsets based on string length
    		if (s.Length % k == 0)
    		{
    			subset = s.Length / k;
    		}
    		else
    		{
    			subset = (int)Math.Floor( (double)s.Length / k) + 1;
    		}
    
    		// Adding string to array of substrings e.g.
    		// "abcdefgh" => [ 'abc', 'def' ]
    		for (int i = 0; i < subset; i++)
    		{
    		    // breaking before reaching the bit of string not of size k
    			if (k * (i + 1) > s.Length) break;
    			string substr = s.Substring(i * k, k);
    			reversed.Add(substr);
    		}
    		
    		// Adding last bit of the string not caught in the loop
    		reversed.Add(s.Substring(s.Length - (s.Length % k), s.Length % k));
    
    		// Reversing every k substring over 2k period
    		int count = 0;
    		for (int i = 0; i < reversed.Count; i += 2)
    		{
    			count++;
    			string newReversed = new string(reversed[i].ToCharArray().Reverse().ToArray());
    			reversed[i] = newReversed;
    		}
    
    		return string.Join("", reversed.ToArray());
    	}
    }
    

Log in to reply
 

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