Welcome to Subscribe On Youtube
3146. Permutation Difference between Two Strings
Description
You are given two strings s
and t
such that every character occurs at most once in s
and t
is a permutation of s
.
The permutation difference between s
and t
is defined as the sum of the absolute difference between the index of the occurrence of each character in s
and the index of the occurrence of the same character in t
.
Return the permutation difference between s
and t
.
Example 1:
Input: s = "abc", t = "bac"
Output: 2
Explanation:
For s = "abc"
and t = "bac"
, the permutation difference of s
and t
is equal to the sum of:
- The absolute difference between the index of the occurrence of
"a"
ins
and the index of the occurrence of"a"
int
. - The absolute difference between the index of the occurrence of
"b"
ins
and the index of the occurrence of"b"
int
. - The absolute difference between the index of the occurrence of
"c"
ins
and the index of the occurrence of"c"
int
.
That is, the permutation difference between s
and t
is equal to \|0 - 1\| + \|2 - 2\| + \|1 - 0\| = 2
.
Example 2:
Input: s = "abcde", t = "edbac"
Output: 12
Explanation: The permutation difference between s
and t
is equal to \|0 - 3\| + \|1 - 2\| + \|2 - 4\| + \|3 - 1\| + \|4 - 0\| = 12
.
Constraints:
1 <= s.length <= 26
- Each character occurs at most once in
s
. t
is a permutation ofs
.s
consists only of lowercase English letters.
Solutions
Solution 1
-
class Solution { public int findPermutationDifference(String s, String t) { int[] d = new int[26]; int n = s.length(); for (int i = 0; i < n; ++i) { d[s.charAt(i) - 'a'] = i; } int ans = 0; for (int i = 0; i < n; ++i) { ans += Math.abs(d[t.charAt(i) - 'a'] - i); } return ans; } }
-
class Solution { public: int findPermutationDifference(string s, string t) { int d[26]{}; int n = s.size(); for (int i = 0; i < n; ++i) { d[s[i] - 'a'] = i; } int ans = 0; for (int i = 0; i < n; ++i) { ans += abs(d[t[i] - 'a'] - i); } return ans; } };
-
class Solution: def findPermutationDifference(self, s: str, t: str) -> int: d = {c: i for i, c in enumerate(s)} return sum(abs(d[c] - i) for i, c in enumerate(t))
-
func findPermutationDifference(s string, t string) (ans int) { d := [26]int{} for i, c := range s { d[c-'a'] = i } for i, c := range t { ans += max(d[c-'a']-i, i-d[c-'a']) } return }
-
function findPermutationDifference(s: string, t: string): number { const d: number[] = Array(26).fill(0); const n = s.length; for (let i = 0; i < n; ++i) { d[s.charCodeAt(i) - 'a'.charCodeAt(0)] = i; } let ans = 0; for (let i = 0; i < n; ++i) { ans += Math.abs(d[t.charCodeAt(i) - 'a'.charCodeAt(0)] - i); } return ans; }
-
public class Solution { public int FindPermutationDifference(string s, string t) { int[] d = new int[26]; int n = s.Length; for (int i = 0; i < n; ++i) { d[s[i] - 'a'] = i; } int ans = 0; for (int i = 0; i < n; ++i) { ans += Math.Abs(d[t[i] - 'a'] - i); } return ans; } }