11. Permutations of a given string
11. Permutations of a given string
Problem link :- click here
package programs;
import java.util.ArrayList;
import java.util.List;
public class String__11
{
/*
Given a string S. The task is to print all permutations of a given string.
s = "abc"
output : abc, acb, bac, bca, cab, cba
*/
static void permutation(String str, int l, int r)
{
if(l==r)
System.out.print(str + "\t");
else
{
for(int i=l; i<=r; i++)
{
str = swap(str, l, i);
permutation(str, l+1, r);
str = swap(str, l, i);
}
}
}
static String swap(String str, int i, int j)
{
char st[] = str.toCharArray();
char temp = st[i];
st[i] = st[j];
st[j] = temp;
String s = String.valueOf(st);
return s;
}
public static void main(String[] args)
{
String s = "abc";
permutation(s, 0, s.length()-1);
}
}
Time complexity :- O(n!*n)
Space complexity :- O(n)
Comments
Post a Comment