Rearrange the characters in a string to generate a new string that returns the number of strings in the newly generated string that do not have consecutive repeating characters. Continuous repetition only takes a single character
For example, aab
you should return 2 because it has a total of 6 permutations (,,,, aab
aab
aba
aba
baa
, baa
), but only two (and aba
aba
) have no consecutive repeating characters (in this case a
).
function Permalone (str) {//use regular match to repeat var regex =/(.) \1+/g;//brackets represent groupings, \1 means getting exactly the same content as the first group//converting the string to an array for easy handling of var arr = Str.split ("); Stores a full array of var permutations = []; var tmp; function function: Swap the location function swap (index1, index2) {tmp = ARR[INDEX1]; ARR[INDEX1] = Arr[index2]; ARR[INDEX2] = tmp; }//Use heap ' s algorithm to generate a fully arranged array function generate (n) {if (n = = = 1) {Permutations.push (Arr.join (")); } else {for (var i = 0;i<N; ++i) {generate (n-1); Swap (n% 2 0:i, n-1); }}} generate (Arr.length); Filter out arrays of non-sequential repeats var filtered= Permutations.filter (function (String){return!string.match (regex); }); Return the number of return filtered.length; } Alert (Permalone ("AABFCDF"));
Heap ' s algorithm full permutation algorithm
procedure Generate (N:integer, A:array of any): if n = 1 then output (A) else < -1; i +do generate (n-1, A) if n was even then swap (A[i], a[n-1]) Else
swap (A[0], a[n-1]) End If end for generate (n-1, A) End If
When I=n, the algorithm produces all the full permutations;
If n is odd, the first element in the permutation is swapped with the last element. If n is an even number, the first element of the arrangement is interchanged with the last element.
No repeats please (Freecodecamp Advanced algorithm 6)