How to find longest substring without repeating characters using Java

Introduction

In this example we will see how to find longest substring from a given string without repeating characters using Java programming language. A given string when broken into substring will have different lengths and we will find the string which has longest length among them.

A string may consist of contiguous characters or several words separated by spaces.

Prerequisites

Java

Find Out Longest Substring

We will write the below code in Java to find out longest substring from a string.

We build each separate string into StringBuilder and put them one by one into ArrayList.

Next we compare the length of each string from the ArrayList and return the string which has the longest length.

public static String longestSubstring(final String str) {
	StringBuilder string = new StringBuilder();

	List<String> strings = new ArrayList<>();

	int len = str.length();

	for (int i = 0; i < len; i++) {
		if (!" ".equals(str.substring(i, i + 1)) && !string.toString().contains(str.substring(i, i + 1))) {
			string.append(str.substring(i, i + 1));
		} else {
			strings.add(string.toString());

			string.setLength(0);

			if (!" ".equals(str.substring(i, i + 1))) {
				string.append(str.substring(i, i + 1));
			}
		}

		if (i == len - 1) {
			strings.add(string.toString());
			string.setLength(0);
		}
	}

	return strings.stream().max(Comparator.comparingInt(String::length)).get();
}

Testing the Program

Now we will create a main method to test our above program.

public static void main(String[] args) {
	System.out.println(longestSubstring("abcdef"));
	System.out.println(longestSubstring("pwwkew"));
	System.out.println(longestSubstring("abcabcbb"));
	System.out.println(longestSubstring("abcdabfg"));
	System.out.println(longestSubstring("This is a sample text file."));
}

Executing the above code will give you below output:

abcdef
wke
abc
abcd
sample

Download Source Code

Thanks for reading.

Leave a Comment