w3resource
Java Programming Exercies

Java String Exercises: Find Length of the longest substring without repeating characters

Java String: Exercise-37 with Solution

Write a Java program to find Length of the longest substring without repeating characters.

Pictorial Presentation:

Java String Exercises: Find Length of the longest substring without repeating characters

Sample Solution:

Java Code:

import java.util.LinkedHashMap;

public class Main {
 static void longestSubstring(String inputString) {
  char[] arr1 = inputString.toCharArray();
  String long_str = null;
  int str_length = 0;
  LinkedHashMap <
  Character, Integer >
  charPosMap = new LinkedHashMap <
  Character, Integer >
  ();
  for (int i = 0; i < arr1.length; i++) {
   char ch = arr1[i];
   if (!charPosMap.containsKey(ch)) {
    charPosMap.put(ch, i);
   } else {
    i = charPosMap.get(ch);
    charPosMap.clear();
   }
   if (charPosMap.size() > str_length) {
    str_length = charPosMap.size();
    long_str = charPosMap.keySet().toString();
   }
  }
  System.out.println("Input String : " + inputString);
  System.out.println("The longest substring : " + long_str);
  System.out.println("The longest Substring Length : " + str_length);
 }
 public static void main(String[] args) {
  longestSubstring("pickoutthelongestsubstring");
 }
}

Sample Output:

Input String : pickoutthelongestsubstring
The longest substring : [u, b, s, t, r, i, n, g]
The longest Substring Length : 8

Flowchart:

Flowchart: Java String Exercises - Find Length of the longest substring without repeating characters

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to check whether two strings are interliving of a given string. Assuming that the unique characters in both strings.
Next: Write a Java program to print after removing duplicates from a given string.

What is the difficulty level of this exercise?