I have this working code to print string permutations without repetitions, but not able to wrap my head around how is it working as in logic. Any suggestions will be really
if (input.equals("")) {
System.out.println(count + " " + sofar);
count++;
}
This step is passed as the input is not ""
. Note that you could simply use input.empty()
here. The only thing to remember here is that count
have not been incremented.
for (int i = 0; i < input.length(); i++) {
This will, loop over all character of the input
char c = input.charAt(i);
if (input.indexOf(c, i + 1) != -1)
This check if the next character is equal to the current one, if it does then it will jump directly to the next iteration
(the next character) using the continue
keyword.
If it does not, then it will recall the method (We call that recursivity
), passing in the string without the current char
. But giving it back to sofar
.
permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
Now in the case where input is empty,
The count of non-distinct character
will be printed + all these character
.