using abba, a
as an example
len
is set at the index that the first char that you are looking is found.
In our case:
- a is first found at index 0
-
charCount
= 0 + 1 = 1
-
i
= 0
-
len = -1
so the code inside the if statement is run: len = i
- therefore
len = 0
len
currently represents the first point at which ‘a’ was found
The for loop then loops two times and hits a ‘b’ each time, that means everything in the following code is skipped and len
still equals 0:
if (str[i] == char) {
charCount++;
if (charCount > 2) {
return 0;
}
if (len == -1) {
len = i;
} else {
len = i - len + 1;
}
}
}
The for loop then loops one more time and hits the second ‘a’, so the code above is run for the second time:
- index of second a = 3
charCount = 1 + 1 = 2
i = 3
- this time
len !== - 1
so the code len = i
is skipped and the following code is run instead:
-
len = i - len + 1
len represents the first point at which ‘a’ was found, i
represents the second point at which ‘a’ was found
- therefore
len = 3 - 0 + 1
-
len = 4
finally, len
represents the distance between the first point and the second point at which ‘a’ was found. You add 1 back so that your total number of steps is inclusive of the first step.
using abbaa, a
as an example
now imagine we had a string abbaa,
if we get to the stage we left off in the above example and then loop one more time, the code above is run for a third time, charCount
is set to equal 3, if (charCount > 2)
returns true
and the function returns 0.
In this example, what happens to len
is irrelevant because we are exiting the function before that calculation can be made, and len
is never returned.