title: Length of the Longest Common Substring without repeating characters
body: <p><strong>Given "abcabcbb", the answer is "abc", which the length is 3.</strong></p>
  
  <p><strong>Given "bbbbb", the answer is "b", with the length of 1.</strong></p>
  
  <p><strong>Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.</strong></p>
  
  <p>I have came up with a solution that worked, but failed for several test cases. I then found a better solution and I rewrote it to try and understand it. The solution below works flawlessly, but after about 2 hours of battling with this thing, I still can not understand why this particular line of code works.</p>
  
  <pre><code>import java.util.*;
  import java.math.*;
  
  public class Solution {
  
    public int lengthOfLongestSubstring(String str) {
  
    if(str.length() == 0)
      return 0;
  
    HashMap&lt;Character,Integer&gt; map = new HashMap&lt;&gt;();
    int startingIndexOfLongestSubstring = 0;
    int max = 0;
  
    for(int i = 0; i &lt; str.length(); i++){
        char currentChar = str.charAt(i); 
        if(map.containsKey(currentChar))
           startingIndexOfLongestSubstring = Math.max(startingIndexOfLongestSubstring, map.get(currentChar) + 1);
  
        map.put(currentChar, i);
        max = Math.max(max, i - startingIndexOfLongestSubstring + 1);
  
        }//End of loop
  
      return max;
  
     }
  }
  </code></pre>
  
  <p>The line in question is <pre>max = Math.max(max, i - startingIndexOfLongestSubstring + 1);</pre></p>
  
  <p>I don't understand why this works. We're taking the max between our previous max, and the difference between our current index and the starting index of what is currently the longest substring and then adding 1. I know that the code is getting the difference between our current index, and the startingIndexOfSubstring, but I can't conceptualize WHY it works to give us the intended result; Can someone please explain this step to me, particularly WHY it works?</p>