File tree Expand file tree Collapse file tree 2 files changed +4
-18
lines changed
maps_java/maps_app/src/main/java/com/codedifferently/lesson13 Expand file tree Collapse file tree 2 files changed +4
-18
lines changed Original file line number Diff line number Diff line change 4
4
5
5
public class Lesson13 {
6
6
7
- /**
8
- * Provide the solution to LeetCode 3146 here:
9
- * https://leetcode.com/problems/permutation-difference-between-two-strings
10
- */
11
7
public int findPermutationDifference (String s , String t ) {
12
8
var charIndexMap = new HashMap <Character , Integer >();
13
9
14
10
int totalDifference = 0 ;
15
11
16
12
for (int sIndex = 0 ; sIndex < s .length (); sIndex ++) {
17
13
charIndexMap .put (s .charAt (sIndex ), sIndex );
18
- //keeps track of the position for each character in 's'
19
14
}
20
15
21
16
for (int tIndex = 0 ; tIndex < t .length (); tIndex ++) {
22
17
int indexInS = charIndexMap .get (t .charAt (tIndex ));
23
- //Same as sIndex , but this loop keeps track of each character in t
24
18
totalDifference += Math .abs (indexInS - tIndex );
25
- //adds all the differences
26
19
}
27
20
28
21
return totalDifference ;
Original file line number Diff line number Diff line change 1
- /**
2
- * Provide the solution to LeetCode 3146 here:
3
- * https://leetcode.com/problems/permutation-difference-between-two-strings
4
- */
5
1
export function findPermutationDifference ( s : string , t : string ) : number {
6
- //Create a way to find the index of each character in string s.
7
- // This could be a list or a dictionary where each character points to its index in s.
8
2
let charPositionMap = new Map < string , number > ( ) ;
9
- //Start with a variable to keep track of the total permutation difference. Set it to 0.
3
+
10
4
let totalDifference = 0 ;
11
- //For each character in t, find its index in s using the mapping you created.
5
+
12
6
for ( let sIndex = 0 ; sIndex < s . length ; sIndex ++ ) {
13
7
charPositionMap . set ( s . charAt ( sIndex ) , sIndex )
14
8
}
15
9
16
10
for ( let tIndex = 0 ; tIndex < t . length ; tIndex ++ ) {
17
- //Calculate the absolute difference between the index in s and the current index in t.
18
11
let indexInS = charPositionMap . get ( t . charAt ( tIndex ) ) ;
19
- //Add the absolute difference you calculated to the total difference.
12
+
20
13
if ( indexInS != undefined ) {
21
14
totalDifference += Math . abs ( indexInS - tIndex ) ;
22
15
}
23
16
}
24
- //After going through all characters in t, return the total difference.
17
+
25
18
return totalDifference ;
26
19
}
You can’t perform that action at this time.
0 commit comments