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

Powered by Blogger.

Saturday, July 22, 2017

Permutations of a given string geeks solution java


Problem : Print all the permutations (string can be made by swapping their value)

Idea was to use backtrack , here we will swap the values and recur for the new string and again backtrack to original string for the function and recur for that string.


Code:

import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
 {
    private static List<String> arr=new ArrayList<String>();
     public static void swap(StringBuffer str,int i,int j)
     {
         char tmep=str.charAt(i);
         char te=str.charAt(j);
         str.setCharAt(i,te);
         str.setCharAt(j,tmep);
     }
     public static void permute(StringBuffer str,int f,int n)
     {
         if(f==n)
         arr.add(String.valueOf(str));
         else{
         for(int i=f;i<=n;i++)
         {
             swap(str,f,i);
             permute(str,f+1,n);
             swap(str,f,i);
         }}
     }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
   StringBuffer str=new StringBuffer(ab.next());
   arr.clear();
   permute(str,0,str.length()-1);
  Collections.sort(arr);
   while(arr.size()!=0)
   System.out.print(arr.remove(0)+" ");
   System.out.println();
}
}
}

0 Comments:

Post a Comment

Stats