In this tutorial, you will learn how to write a java program to find longest substring without repeating characters. For example, if a string is “TEXT”, the longest substring in “TEXT” without repeating character is: “TEX”. Similarly longest substring with non-repeating characters in a string “AAAAA” is “A”. Here we will write a java program that finds the longest substring with non-repeating character and display the length of this substring.
Program to find longest substring without repeating characters
In this program, we have created a user defined method longestSubstrWithoutRepeat()
. This method takes a string as an input and returns the length of the longest substring with no repeating characters.
public class JavaExample {
public static int longestSubstrWithoutRepeat(String str)
{
String longestSubstr = "";
// Result
int maxLength = -1;
// Return 0 if the input string is empty
if (str.isEmpty()) {
return 0;
}
// Return 1 is if the input string contains only one char
else if (str.length() == 1) {
return 1;
}
for (char c : str.toCharArray()) {
String current = String.valueOf(c);
if (longestSubstr.contains(current)) {
longestSubstr =
longestSubstr.substring(
longestSubstr.indexOf(current) + 1);
}
longestSubstr = longestSubstr + String.valueOf(c);
maxLength = Math.max(longestSubstr.length(), maxLength);
}
return maxLength;
}
public static void main(String[] args)
{
String str = "beginnersbook";
System.out.println("The given string is " + str);
int len = longestSubstrWithoutRepeat(str);
System.out.println("The length of the longest " +
"substring without repeating " +
"characters is: "+ len);
}
}
Output: Here, the longest substring with no reoccurring character would be: “nersbo” (length: 6, as number of characters in this string is 6).
Leave a Reply