String permutations = IntStream.range(0, codePoints.length) For example, four steps of reduction for a five-character string □□□□□: 0 The reduce method takes a pair of permutation arrays and sums their elements in pairs, accumulating the results. This solution assumes that the original string does not contain duplicate characters, otherwise the permutation maps Map should be used instead of the permutation arrays String. You can generate an array of permutations of the string using map and reduce methods. See also: How do you check if a word has an anagram that is a palindrome? mapToObj(i -> IntStream.range(0, permutations.size()) Int rows = IntStream.range(1, codePoints.length) number of rows (factorial of string length - 1) filter out those keys that are already present summation of pairs of maps from two lists reduce a stream of lists to a single list mapToObj(j -> Map.of(j, Character.toString(codePoints))) mapToObj(i -> IntStream.range(0, codePoints.length) List> permutations = IntStream.range(0, codePoints.length) Int codePoints = str.codePoints().toArray() O(N!)?ġ5 sums for each of the 4 characters are 60 sums, resulting in 4! = 24 permutations. So in total, we do n * (n - 1) * (n - 2) *. The loop shrinks (we iterate 3 times in the thick branch at the left, then 2 in the next level, then only one) but still there is a loop. And so it goes, branch by branch, in what we usually call "depth-first search". But wait, still work to do! Because ("", "ABC") still has two more letters to process. Now all the loops under ("A", "BC") are done. So we're done there as well, and return back to ("A", "BC") level there are two elements in "BC" and we've only done the "B", so it's now "C"'s turn: we call ("AC", "B"), which then calls ("ACB", ""). Then we remember we have unfinished business, we return to a loop, but the loop in the previous level only had one cycle. When we start, we will enter ("A", "BC") state we proceed to call ("AB", "C"), and finally ("ABC", ""). Note that this looks like a tree laid on its side. Easier example: permutation("", "ABC"), representing empty string as *: * ABC + A BC + AB C - ABC *
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |