LeetCode 3146 两个字符串的排列差
方法1:模拟 + 标记数组(哈希表)
class Solution {
public int findPermutationDifference(String s, String t) {
int[] idx = new int[26];
int n = s.length(), ans = 0;
for (int i = 1; i <= n; i++) {
int idxS = s.charAt(i - 1) - 'a';
int idxT = t.charAt(i - 1) - 'a';
if (idx[idxS] != 0)
ans += i - idx[idxS];
else
idx[idxS] = i;
if (idx[idxT] != 0)
ans += i - idx[idxT];
else
idx[idxT] = i;
}
return ans;
}
}
class Solution:
def findPermutationDifference(self, s: str, t: str) -> int:
idx = {ch : i for i, ch in enumerate(s)}
return sum(abs(j - idx[ch]) for j, ch in enumerate(t))
标签:24,ch,String,idx,int,08,2024,enumerate
From: https://www.cnblogs.com/XuGui/p/18377434