Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Friday, June 29, 2018

Transform String by moving character


Problem:
transform string A into string B in minimum number of steps. Only one operation is allowed, chose any of the characters in string A and place it in the front of A


Idea is to first check if all the characters in both strings are same or not.
Then check the matching sequence from right to left (String B to A)
Those characters who doesn't have same sequence will be moved to front.



Code:

import java.util.*;
import java.lang.*;
import java.io.*;
class transformStringbyMovingChartoFront
 {
  public static int fn(char a[],char []b)
  {
      if(a.length!=b.length) return -1;
      Map<Character,Integer> map=new HashMap<>();
      for(int i=0;i<a.length;++i)
      {
          if(map.containsKey(a[i]))
          map.put(a[i],map.get(a[i])+1);
          else
          map.put(a[i],1);
      }
       for(int i=0;i<b.length;++i)
      {
          if(!map.containsKey(b[i]) || map.get(b[i])==0)
          return -1;
          map.put(b[i],map.get(b[i])-1);
      }
      int j=a.length-1;
      int i=b.length-1;
      int c=0;
      for(;i>=0 && j>=0;)
      {
          if(b[i]==a[j])
          {
              --i;
              --j;
              ++c;
          }
          else
          --j;
      }
      return a.length-c;
  }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=Integer.parseInt(ab.nextLine());
while(t-->0)
{
    String a[]=ab.nextLine().split(" ");
   /* for(int i=0;i<a.length;++i)
    System.out.print(a[i]);*/
    if(a.length==1)
    System.out.println(fn(a[0].toCharArray(),ab.next().toCharArray()));
    else
    System.out.println(fn(a[0].toCharArray(),a[1].toCharArray()));
}
}
}

0 Comments:

Post a Comment

Stats