Not able to understand string permutation Java code

后端 未结 3 442
清歌不尽
清歌不尽 2021-01-07 06:32

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

3条回答
  •  走了就别回头了
    2021-01-07 07:24

    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.

提交回复
热议问题