Find longest substring without repeating characters

前端 未结 30 2455
轻奢々
轻奢々 2020-12-12 18:07

Given a string S of length N find longest substring without repeating characters.

Example:

Input:

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 18:44

    We can consider all substrings one by one and check for each substring whether it contains all unique characters or not. There will be n*(n+1)/2 substrings. Whether a substirng contains all unique characters or not can be checked in linear time by scanning it from left to right and keeping a map of visited characters. Time complexity of this solution would be O(n^3).`

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.LinkedHashSet;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    
    public class LengthOfLongestSubstringWithOutRepeatingChar {
    	public static void main(String[] args)
    	{
    	String s="stackoverflow";	
    	//allSubString(s);
    	System.out.println("result of find"+find(s));
    	}
    	public static String find(String s)
    	{
    		List allSubsring=allSubString(s);
    		Set main =new LinkedHashSet();
    		for(String temp:allSubsring)
    		{
    			boolean a = false;
    			for(int i=0;ii;k--)
    				{
    					if(temp.charAt(k)==temp.charAt(i))
    						a=true;
    				}
    			}
    			if(!a)
    			{
    				main.add(temp);
    			}
    		}
    		/*for(String x:main)
    		{
    		System.out.println(x);	
    		}*/
    		String res=null;
    		int min=0,max=s.length();
    		for(String temp:main)
    		{
    		if(temp.length()>min&&temp.length() allSubString(String str) {
    	List all=new ArrayList();
    	int c=0;
    	for (int i = 0; i < str.length(); i++) {
    		for (int j = 0; j <= i; j++) {
    			if (!all.contains(str.substring(j, i + 1)))
    			{
    				c++;
    				all.add(str.substring(j, i + 1));
    			}
    		}
    	}
    	for(String temp:all)
    	{
    		System.out.println("substring :-"+temp);
    	}
    	System.out.println("count"+c);
    	return all;
    }
    }

提交回复
热议问题