
题目描述
给你两个字符串 s 和 t,每个字符串中的字符都不重复,且 t 是 s 的一个排列。
排列差 定义为 s 和 t 中每个字符在两个字符串中位置的绝对差值之和。
返回 s 和 t 之间的 排列差 。
 
示例 1:
输入:s = "abc", t = "bac"
输出:2
解释:
对于 s = "abc" 和 t = "bac",排列差是:
    "a" 在 s 中的位置与在 t 中的位置之差的绝对值。 
    "b" 在 s 中的位置与在 t 中的位置之差的绝对值。 
    "c" 在 s 中的位置与在 t 中的位置之差的绝对值。 
即,s 和 t 的排列差等于 |0 - 1| + |1 - 0| + |2 - 2| = 2。
 
示例 2:
输入:s = "abcde", t = "edbac"
输出:12
解释: s 和 t 的排列差等于 |0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12。
 
 
提示:
    1 <= s.length <= 26 
    - 每个字符在 
s 中最多出现一次。 
    t 是 s 的一个排列。 
    s 仅由小写英文字母组成。 
解法
方法一:哈希表或数组
我们可以使用哈希表或者一个长度为 \(26\) 的数组 \(\textit{d}\) 来存储字符串 \(\textit{s}\) 中每个字符的位置。
然后遍历字符串 \(\textit{t}\),计算每个字符在字符串 \(\textit{t}\) 中的位置与在字符串 \(\textit{s}\) 中的位置之差的绝对值之和即可。
时间复杂度 \(O(n)\),其中 \(n\) 为字符串 \(\textit{s}\) 的长度。空间复杂度 \(O(|\Sigma|)\),其中 \(\Sigma\) 为字符集,这里是小写英文字母,所以 \(|\Sigma| \leq 26\)。
 | 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))
  | 
 
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14  | 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;
    }
}
  | 
 
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15  | 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;
    }
};
  | 
 
 
 | 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
}
  | 
 
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12  | 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) - 97] = i;
    }
    let ans = 0;
    for (let i = 0; i < n; ++i) {
        ans += Math.abs(d[t.charCodeAt(i) - 97] - i);
    }
    return ans;
}
  | 
 
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14  | 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;
    }
}
  |