package com.clearurdoubt;
import java.util.Scanner;
/**
*
* @author clearurdoubt
*
*/
public class FindSubstring {
public static void main(String[] args) {
System.out.println("Please enter an input string:"); // request user to provide an empty string
Scanner in = new Scanner(System.in); // Scanner instance to read the input from console
String input = in.nextLine().trim(); // Read the input and trim the spaces around it
// Find and print the longest substring.
System.out.println("The longest substring in the input \"" + input + "\" is \"" + findLongestSubstring(input) + "\"");
in.close();
}
/**
* Method to find the longest substring without repeated characters
* @param input string from user
* @return
*/
private static String findLongestSubstring(String input)
{
String longest = ""; // Variable for storing the longest substring
// Loop through the characters from starting to ending
for(int i=0; i < input.length() - 1; i++)
{
String substr = ""; // Local variable to find the current substring without repeated chars
// Loop through characters from index "i" till the end of input
for(int j = i; j < input.length() - 1; j++)
{
char ch = input.charAt(j); // Current character
if(substr.indexOf(ch) == -1) // If substr doesn't contain the current character
{
substr += ch; // Time to append the current char to substr
}
else
{
break; // Current char already in the substr, so break out the inner loop
}
}
// Time to check if the local substr is longer than "longest" variable
if(longest.length() < substr.length())
{
longest = substr;
}
}
return longest; // Return the longest substring
}
}