[Sword refers to Offer learning] [interview question 28: String arrangement], sword refers to offer
Question: enter a string to print all the characters in the string. For example, input the string abc. Print all strings abc, acb, bac, bca, cab, and CBA that can be arranged by characters a, B, and c. Solution:
Consider a string as composed of two parts: the first part is its first character, and the second part is all the subsequent characters. In Figure 4.14, we use two different background colors to distinguish the two parts of the string.
We can arrange the entire string as two steps: first, find all the characters that may appear at the first position, that is, exchange the first character with all the subsequent characters. Figure 4.14 exchanges the first character a with the subsequent characters B and c. First, fix the first character (as shown in 4.14 (a)> and sort all the subsequent characters. At this time, we still divide all the following characters into two parts: the first character after the character, and all the characters after the character. Then swap the first character one by one with the character following it (as shown in 4.14 (B )......
This is actually a typical recursive idea.
Code implementation:
Public class Test28 {/*** title: enter a string to print all the characters in the character. For example, input the string abc. * Print all strings abc, acb, bac, bca, cab, and CBA that can be arranged by characters a, B, and c. ** @ Param chars the character array to be sorted */public static void permutation (char [] chars) {// input if (chars = null | chars. length <1) {return;} // permutation (chars, 0 );} /*** sort character arrays ** @ param chars string to be sorted * @ param begin current processing position */public static void permutation (char [] chars, int begin) {// if it is the last element, it will output the arrangement result if (chars. length-1 = begin) {System. out. print (new String (chars) + "");} else {char tmp; // process strings that have not yet been processed, each character can be used as the element of the current processing position for (int I = begin; I <chars. length; I ++) {// The following is the position of the switching element tmp = chars [begin]; chars [begin] = chars [I]; chars [I] = tmp; // process the next location permutation (chars, begin + 1) ;}} public static void main (String [] args) {char [] c1 = {'A ', 'B', 'C'}; permutation (c1); System. out. println (); char [] c2 = {'A', 'B', 'C', 'D'}; permutation (c2 );}}
Running result:
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.