@@ -7,6 +7,51 @@ public class Lesson13 {
77 * https://leetcode.com/problems/permutation-difference-between-two-strings
88 */
99 public int findPermutationDifference (String s , String t ) {
10- return 0 ;
10+ // I create a hashmap called "tBys" (convention) that I store the key-value pairs of s & t into.
11+ java .util .Map <Character , Integer > tBys = new java .util .HashMap <>();
12+
13+ // This variable will take in the difference for each index after every iteration, eventually
14+ // giving the complete sum of them all.
15+ int accumulationVariable = 0 ;
16+ int permDifference = 0 ;
17+ // NOTE: I use accumulationVariable for my own personal convention.
18+
19+ // This for loop is actually what goes through the string s & puts each key-value into the
20+ // variable tBys, which is now an object.
21+ for (int i = 0 ; i < s .length (); i ++) {
22+ // Puts these key-values into the tBys map.
23+ tBys .put (s .charAt (i ), i );
24+ }
25+
26+ // This for loop goes through the string t and will use the key to get the value of the tBys
27+ // object.
28+ for (int i = 0 ; i < t .length (); i ++) {
29+
30+ // Assigns the character at index i to currentChar. For iteration 1, that would be character
31+ // b.
32+ char currentChar = t .charAt (i ); // This is character 'b' in string t.
33+
34+ // .get() gets the index value from currentChar, which in turn gives the index value for s.
35+ // currentChar is b for iteration 1 (in string t), because the index of 0 for the t string is
36+ // b. If I were to try and translate this line into plain english, it would look something
37+ // like this: "Using string t as a reference, go and GET the 'b' from the t string. This
38+ // letter will reference the 'b' in string s, giving us index 1 from string s being assigned
39+ // to sIndex."
40+ int sIndex = tBys .get (currentChar ); // This is index 1 from string s, aka 'b'.
41+
42+ // Because the problem wants the absolute difference between the index of s & t, we will
43+ // simply use the Math.abs method to get the absolute value of each integer. Each distance
44+ // equation is represented by being placed inside 2 verticle bars (|99-99|). sIndex - i would
45+ // give us the difference between each index after every loop. The i simply represents the
46+ // next letter that we're supposed to compare.
47+ accumulationVariable +=
48+ Math .abs (
49+ sIndex - i ); // This is simply the position of s minus the position of t. i finds a
50+ // letter in t, takes that index, then subtracts it by the index of the
51+ // letter that it's looking for.
52+ }
53+ permDifference = accumulationVariable ;
54+ return permDifference ; // Returns the full permutation difference after the loops have run their
55+ // course.
1156 }
1257}
0 commit comments