Optimal Java solution using recursion


  • 0
    L

    Solution is easy to understand and it avoids creating temporaries etc.

    public class Solution
    {
      public String reverseStr(String s, int k)
      {
        StringBuilder builder = new StringBuilder(s);
        helper(builder, 0, k);
        return builder.toString();
      }
    
    
    
      private void helper(StringBuilder s, int i, int k)
      {
        if (2 * k <= s.length() - i)
        {
          reverse(s, i, i + k - 1);
          helper(s, i+2 * k, k);
        }
        else if (k > s.length() - i)
        {
          reverse(s, i, s.length() - 1);
        }
        else
        {
          reverse(s, i, i + k - 1);
        }
      }
    
    
    
      private void reverse(StringBuilder s, int i, int j)
      {
        while (j > i)
        {
          char c = s.charAt(i);
          s.setCharAt(i, s.charAt(j));
          s.setCharAt(j, c);
          j--;
          i++;
        }
      }
    }
    

Log in to reply
 

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