Skip to content

Commit 6a9c74d

Browse files
committedJul 18, 2024
solves #3146: Permutation Difference between Two Strings in java
1 parent 7529944 commit 6a9c74d

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed
 

Diff for: ‎README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -910,7 +910,7 @@
910910
| 3131 | [Find the Integer Added to Array I](https://leetcode.com/problems/find-the-integer-added-to-array-i) | [![Java](assets/java.png)](src/FindTheIntegerAddedToArrayI.java) | |
911911
| 3136 | [Valid Word](https://leetcode.com/problems/valid-word) | [![Java](assets/java.png)](src/ValidWord.java) | |
912912
| 3142 | [Check if Grid Satisfies Conditions](https://leetcode.com/problems/check-if-grid-satisfies-conditions) | [![Java](assets/java.png)](src/CheckIfGridSatisfiesConditions.java) | |
913-
| 3146 | [Permutation Difference between Two Strings](https://leetcode.com/problems/permutation-difference-between-two-strings) | | |
913+
| 3146 | [Permutation Difference between Two Strings](https://leetcode.com/problems/permutation-difference-between-two-strings) | [![Java](assets/java.png)](src/PermutationDifferenceBetweenTwoStrings.java) | |
914914
| 3151 | [Special Array I](https://leetcode.com/problems/special-array-i) | | |
915915
| 3158 | [Find the XOR of Numbers Which Appear Twice](https://leetcode.com/problems/find-the-xor-of-numbers-which-appear-twice) | | |
916916
| 3162 | [Find the Number of Good Pairs I](https://leetcode.com/problems/find-the-number-of-good-pairs-i) | | |

Diff for: ‎src/PermutationDifferenceBetweenTwoStrings.java

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// https://leetcode.com/problems/permutation-difference-between-two-strings
2+
// T: O(N)
3+
// S: O(1)
4+
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
public class PermutationDifferenceBetweenTwoStrings {
9+
public int findPermutationDifference(String s, String t) {
10+
final Map<Character, Integer> letterIndexes = getCharacterIndexMapping(s);
11+
int sum = 0;
12+
13+
for (int i = 0 ; i < t.length() ; i++) {
14+
sum += Math.abs(i - letterIndexes.get(t.charAt(i)));
15+
}
16+
17+
return sum;
18+
}
19+
20+
private static Map<Character, Integer> getCharacterIndexMapping(String s) {
21+
final Map<Character, Integer> map = new HashMap<>();
22+
for (int i = 0 ; i < s.length() ; i++) {
23+
map.put(s.charAt(i), i);
24+
}
25+
return map;
26+
}
27+
}

0 commit comments

Comments
 (0)