Saturday, May 13, 2017

Reverse String II

  • Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. 
  • If there are less than k characters left, reverse all of them. 
  • If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Link to Git HubCode


Input: s = "abcdefg", k = 2
Output: "bacdfeg"

  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]
  • Convert the string into a character array
  • Find the min (i) and max(j) value for swapping based on k value. 
           int j=Math.min(i+k-1, n-1)
  • Swap the elements 

package Algorithms.Strings;
 * Input: s = "abcdefg", k = 2
    Output: "bacdfeg
public class ReverseString2 {
 public static String get(String s,int k)
  //Convert the string in char array
  char [] arr=s.toCharArray();
  //Array length
  int n=arr.length;
  int i=0;
   int j=Math.min(i+k-1, n-1);
   //Call the swap function
   //Increment the counter
 //Convert character to string and return
 return String.valueOf(arr); 
 private static void swap(char [] arr, int l, int r)
   //Store the first char as temp
   char temp=arr[l];
   //Swap the last element to the first element
   //Swap the first element from the temp to last element



No comments:

Post a Comment