Longest Substring Without Repeating Characters In Java time complexity O(n)

Longest Substring Without Repeating Characters In Java time complexity O(n) 
If you try to solve this using HashMap than you will able to find the correct answer but the order of the string would not be same as input string. So you have to used the LinkedHashMap which preserves the insertion order. 
.

import java.util.Scanner;
import java.util.LinkedHashMap;

public class String7_for_blog
{
public static void main(String[] args)
{

int i;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your string");
String str=sc.nextLine();
char[] astr=str.toCharArray();
int sublen=0;
String substr=null;
LinkedHashMap<Character,Integer> mymap= new LinkedHashMap<Character,Integer>();
for(i=0;i<astr.length;i++)
{
if(!mymap.containsKey(astr[i]))
{
mymap.put(astr[i],i);
}
else
{
i=mymap.get(astr[i]);
mymap.clear();
}
if(mymap.size()>sublen)
{
sublen=mymap.size();
substr=mymap.keySet().toString();
System.out.println(substr);

}

System.out.println("The input string is =>"+str);
 System.out.println("the length of longest sub-string without repeatation is=>"+""+sublen);
System.out.println("The longest sub-string without repeatation is =>"+substr);
}

}

No comments:

Post a Comment

All Repeated Words In Text File And Their Occurrences In Java

Find All Repeated Words In Text File And Their Occurrences In Java Place your file location in the argument of the FileReader. If t...