title: Java out of memory error when doing substring on extremely large strings
body: <p>The following method throws an exception when the input string is too long (length > 200,000). The problem seems to be related to the use of substring(), After looking at some other posts I changed the usage to become <code>String str = new String( s.substring( i,i+k ) );</code> but the problem still occurs...Any idea why the memoery exception is still thrown? (I do not want to increase the heap size)</p>
  
  <p>The method:</p>
  
  <pre><code> private static Map&lt;String,Integer&gt; findSubString(String s, int k) {
      Map&lt;String,Integer&gt; map = new HashMap&lt;&gt;(  );
      for (int i = 0; i &lt; s.length() - (k - 1); i++) {
          String str = new String( s.substring( i,i+k ) );
          if (map.containsKey( str )) {
              map.put( str, map.get( str ) + 1 );
          }
          else {
              map.put( str, 1 );
  
          }
      }
  
      return map;
  }
  </code></pre>
  
  <p>The error:</p>
  
  <pre><code>java.lang.OutOfMemoryError: Java heap space
  at java.util.Arrays.copyOfRange(Arrays.java:3664)
  at java.lang.String.&lt;init&gt;(String.java:207)
  at java.lang.String.substring(String.java:1969)
  at Solution.findSubString(Solution.java:112)
  </code></pre>