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

Powered by Blogger.

Thursday, July 13, 2017

Next Permutation Java


Idea was to fix a character at a index by swap and call recursively until all the permutation found i,e when last element is also fixed.

Code:
import java.util.*;
class nextpermutation
{
public static void swap(StringBuffer str,int i,int j)
{
char l=str.charAt(i);
char k=str.charAt(j);
str.setCharAt(i,k);
str.setCharAt(j,l);
}
public static void permute(StringBuffer str,int l,int r)
{
if(l==r)
System.out.println(str);
else
{
for(int i=l;i<=r;i++)
{
swap(str,l,i);
permute(str,l+1,r);
swap(str,l,i); // bring string back to original position
}
}
}
public static void main(String args[])
{
StringBuffer str=new StringBuffer("abc");
permute(str,0,str.length()-1);
}
}

Reference : http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/

0 Comments:

Post a Comment

Stats