Since the program has some global variables, I think it is not looping N times, accepting N from the user, where N is the number of test cases.
I tried accepting N in main and then adding a for loop running N times the body of main, but this doesn't work and always gives an error.
Here is the code:(To print the permutation of a string which is next in the lexographical order)
import java.util.*;
public class Permutation
{
// Returns true if str[curr] does not matches with any of the
// characters after str[start]
static String x[];static int i=0;
static String sort(String s)
{
char a[]=s.toCharArray();
Arrays.sort(a);
return String.valueOf(a);
}
static boolean shouldSwap(char str[], int start, int curr) {
for (int i = start; i < curr; i++) {
if (str[i] == str[curr]) {
return false;
}
}
return true;
}
// Prints all distinct permutations in str[0..n-1]
static void findPermutations(char str[], int index, int n) {
if (index >= n) {
x[i++]=String.valueOf(str);
}
for (int i = index; i < n; i++) {
// Proceed further for str[i] only if it
// doesn't match with any of the characters
// after str[index]
boolean check = shouldSwap(str, index, i);
if (check) {
swap(str, index, i);
findPermutations(str, index + 1, n);
swap(str, index, i);
}
}
}
static void swap(char[] str, int i, int j) {
char c = str[i];
str[i] = str[j];
str[j] = c;
}
// Driver code
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s1=sc.nextLine();
String s=sort(s1);
char str[]=s.toCharArray();
int n = str.length; int nf=1;
for(int i=1;i<=n;i++)
{
nf=nf*i;
}
x=new String[nf];
Arrays.fill(x," ");
findPermutations(str,0,n);
for(int i=0;i<x.length;i++)
{
if(x[i].equals(s1))
{
System.out.println(x[i+1]);
}
}
}
How shall I solve this error? I don't want to reprogram the entire thing.
Aucun commentaire:
Enregistrer un commentaire