#C9998. Minimum Adjacent Swaps Transformation
Minimum Adjacent Swaps Transformation
Minimum Adjacent Swaps Transformation
You are given two strings s and t of equal length. Your task is to compute the minimum number of adjacent swaps required to transform s into t. In each swap, you may only swap two consecutive characters in the string.
If the transformation is impossible, output \(-1\). It can be shown that the number of required swaps is unique when the transformation is possible.
Note: Two strings can be transformed into each other only if they are anagrams. In other words, if \(sorted(s) \neq sorted(t)\), then the answer is \(-1\).
Examples:
- For
s = "abcd"
andt = "dcba"
, the minimum swaps required is6
. - For
s = "ab"
andt = "ba"
, the answer is1
. - For
s = "abcd"
andt = "abce"
, the answer is-1
since a transformation is impossible.
inputFormat
The input consists of two lines:
- The first line contains the string s.
- The second line contains the string t.
Both strings will have the same length and contain only lowercase English letters.
outputFormat
Output a single integer, representing the minimum number of adjacent swaps required to transform s into t, or -1
if such a transformation is impossible.
abcd
dcba
6
</p>