Leetcode / 3146. Permutation Difference Between Two Strings
Pick a programming language:
Here is the source code for the solution to this problem.
class Solution {
// time O(1) because always O(26) characters
// space O(1)
public int findPermutationDifference(String s, String t) {
// we cannot assume s is sorted in alphabetical order if split into
// separate characters, so we have to build an array of their indices.
int[] indices = new int[26];
for (int i = 0 ; i < s.length(); i++) {
indices[s.charAt(i) - 'a'] = i;
}
int sum = 0;
for (int i = 0; i < t.length(); i++) {
int diff = indices[t.charAt(i) - 'a'] - i;
int absoluteDiff = diff < 0 ? -diff : diff;
sum += absoluteDiff;
}
return sum;
}
}
Did you like the lesson? 😆👍
Consider a donation to support our work: