关于求解字符串排列函数perm的逆排列序列seq_c的技术问询
seq_c for Your perm Function Great question! Let's break this down step by step—what you're looking for is the inverse permutation of seq, which will undo the original permutation and restore your original string.
First, Let's Clarify How perm Works
From your examples, we know that for perm(in, seq):
- The output string
outfollowsout[i] = in[seq[i]](whereseq[i]is the integer value of the character at positioniinseq). - In plain terms: the
i-th character of the result comes from theseq[i]-th character of the input.
What Does seq_c Need to Do?
We need perm(perm(str, seq), seq_c) == str. Let's translate this into index logic to make it clear:
- Let
s = perm(str, seq), sos[i] = str[seq[i]]for all positionsi. - Applying
permagain withseq_cgives:perm(s, seq_c)[j] = s[seq_c[j]] = str[seq[seq_c[j]]]. - For this to equal
str[j](the original character at positionj), we needseq[seq_c[j]] = jfor everyj.
This is exactly the definition of an inverse permutation: seq_c[j] is the index k where seq[k] = j.
Step-by-Step to Construct seq_c
Let's use your examples to make this concrete:
Example 1: seq = "201"
- Convert
seqto a numeric array:perm_arr = [2, 0, 1] - Create an empty inverse array
inv_perm_arrof the same length. - For each target index
j(0, 1, 2):- Find
kwhereperm_arr[k] = j:j=0:perm_arr[1] = 0→inv_perm_arr[0] = 1j=1:perm_arr[2] = 1→inv_perm_arr[1] = 2j=2:perm_arr[0] = 2→inv_perm_arr[2] = 0
- Find
- Convert
inv_perm_arrback to a string:seq_c = "120"
Verification:
perm("abc", "201") = "cab"perm("cab", "120")→out[0] = cab[1] = 'a',out[1] = cab[2] = 'b',out[2] = cab[0] = 'c'→"abc"(matches the original string!)
Example 2: seq = "210"
- Numeric array:
perm_arr = [2, 1, 0] - Build inverse array:
j=0:perm_arr[2] =0→inv_perm_arr[0] =2j=1:perm_arr[1] =1→inv_perm_arr[1] =1j=2:perm_arr[0] =2→inv_perm_arr[2] =0
- String result:
seq_c = "210"
Verification:
perm("abc", "210") = "cba"perm("cba", "210") = "abc"(perfect, it undoes itself!)
General Algorithm
To create seq_c from any valid seq:
- Convert
seqinto an array of integers (let's call thisp). - Initialize an array
inv_pof the same length asp. - For each index
kfrom 0 tolen(p)-1:- Set
inv_p[p[k]] = k(becausep[k]is the original index mapped to positionk, so the inverse mapsp[k]back tok).
- Set
- Convert
inv_pback to a string (each integer becomes a character) to getseq_c.
This works because permutations are bijections (one-to-one and onto mappings), so every value in p has exactly one corresponding index k—no duplicates or missing values.
内容的提问来源于stack exchange,提问作者lsund

