Java program to find longest substring of given string

In this article, we will see java programs to find the longest substring of a string without repeating characters.

For example,

longest substring of “hello” without repeating characters will be “hel”. So, length of longest sub-string will be 3.

import java.util.HashSet;

public class Example {

  public static void main(String[] args) {

    String s = "hello";
    int j = 0;
    int lenSubstr = 0;
    HashSet<Character> subset = new HashSet<Character>();
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      if (!subset.contains(c)) {
        subset.add(c);
        lenSubstr = Math.max(lenSubstr, subset.size());
      } else {
        while (j < i) {

          if (s.charAt(j) == c) {
            j++;
            break;
          } else {
            subset.remove(s.charAt(j));
            j++;
          }
        }

        subset.add(c);
      }
    }
    System.out.println("Original String = " + s);
    System.out.println("Length of Longest substring = " + lenSubstr);
  }

}

Output :

Original String = hello
Length of Longest substring = 3

 

© 2017 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags