[LeetCode] Permutation Difference between Two Strings

3146. Permutation Difference between Two Strings

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int findPermutationDifference(string s, string t) {
unordered_map<char,int> freq;
for(int i = 0; i < s.length(); i++) freq[s[i]] = i;
int res = 0;
for(int i = 0; i < t.length(); i++) {
res += abs(freq[t[i]] - i);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/12/PS/LeetCode/permutation-difference-between-two-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.