Doubt regarding substring

how does the placing around c for bc and cb work in this video

@malhotranaman83,

actually we are taking the first char and make the the recursive call for the rest of string
and then we are generating all the possible permutations by appending the first char

suppose the string is abc
then the first char = a
and rest of str= bc
so we are making the recursive call for the rest of string

Also, can you please elaborate a little more on your doubt if it is not resolved yet?

I’m asking if str=c and ch=b how does substing(0,i)+ch+substring (i) works ? To give bc and cb.

@malhotranaman83,

	for (String rrs : rr) {
		for (int i = 0; i < rrs.length(); i++) {
			mr.add(rrs.substring(0, i) + cc + rrs.substring(i));
		}
	}

Look at this code. If cc is a, then rr = [bc , cb ]
Now for rrs = bc
when i = 0, mr.add("" + “a” + “bc”) , thus abc will be added to mr.
when i = 1, mr.add(“b” + “a” + “c”), thus bac will be added to mr.
when i=2, mr.add(“bc” + “a” + “”), thus bca will be added to mr.

Here the length of "bc " is 3 because there is a " " char at the end. Hence the loop runs 3 times.

okay thank you very much

1 Like