Find longest substring without repeating characters

前端 未结 30 2241
轻奢々
轻奢々 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

    EDITED:

    following is an implementation of the concesus. It occured to me after my original publication. so as not to delete original, it is presented following:

    public static String longestUniqueString(String S) {
        int start = 0, end = 0, length = 0;
        boolean bits[] = new boolean[256];
        int x = 0, y = 0;
        for (; x < S.length() && y < S.length() && length < S.length() - x; x++) {
            bits[S.charAt(x)] = true;
            for (y++; y < S.length() && !bits[S.charAt(y)]; y++) {
                bits[S.charAt(y)] = true;
            }
            if (length < y - x) {
                start = x;
                end = y;
                length = y - x;
            }
            while(y<S.length() && x<y && S.charAt(x) != S.charAt(y))
                bits[S.charAt(x++)]=false;
        }
        return S.substring(start, end);
    }//
    

    ORIGINAL POST:

    Here is my two cents. Test strings included. boolean bits[] = new boolean[256] may be larger to encompass some larger charset.

    public static String longestUniqueString(String S) {
        int start=0, end=0, length=0;
        boolean bits[] = new boolean[256];
        int x=0, y=0;
        for(;x<S.length() && y<S.length() && length < S.length()-x;x++) {
            Arrays.fill(bits, false);
            bits[S.charAt(x)]=true;
            for(y=x+1;y<S.length() && !bits[S.charAt(y)];y++) {
                bits[S.charAt(y)]=true;
            }           
            if(length<y-x) {
                start=x;
                end=y;
                length=y-x;
            }
        }
        return S.substring(start,end);
    }//
    
    public static void main(String... args) {
        String input[][] = { { "" }, { "a" }, { "ab" }, { "aab" }, { "abb" },
                { "aabc" }, { "abbc" }, { "aabbccdefgbc" },
                { "abcdeafghicabcdefghijklmnop" },
                { "abcdeafghicabcdefghijklmnopqrabcdx" },
                { "zxxaabcdeafghicabcdefghijklmnopqrabcdx" },
                {"aaabcdefgaaa"}};
        for (String[] a : input) {
            System.out.format("%s  *** GIVES ***  {%s}%n", Arrays.toString(a),
                    longestUniqueString(a[0]));
        }
    }
    
    0 讨论(0)
  • 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<String> allSubsring=allSubString(s);
    		Set<String> main =new LinkedHashSet<String>();
    		for(String temp:allSubsring)
    		{
    			boolean a = false;
    			for(int i=0;i<temp.length();i++)
    			{ 
    				for(int k=temp.length()-1;k>i;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()<max)
    		{
    			min=temp.length();
    			res=temp;
    		}
    		}
    		System.out.println(min+"ha ha ha"+res+"he he he");
    		return res;
    		
    	}
    	//substrings left to right ban rahi hai
    
    private static List<String> allSubString(String str) {
    	List<String> all=new ArrayList<String>();
    	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;
    }
    }

    0 讨论(0)
  • 2020-12-12 18:44
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.LinkedHashSet;
    import java.util.List;
    import java.util.Set;
    import java.util.TreeMap;
    
    public class LongestSubString2 {
    
        public static void main(String[] args) {
            String input = "stackoverflowabcdefghijklmn";
            List<String> allOutPuts = new ArrayList<String>();
            TreeMap<Integer, Set> map = new TreeMap<Integer, Set>();
            for (int k = 0; k < input.length(); k++) {
                String input1 = input.substring(k);
                String longestSubString = getLongestSubString(input1);
                allOutPuts.add(longestSubString);
            }
    
            for (String str : allOutPuts) {
                int strLen = str.length();
                if (map.containsKey(strLen)) {
                    Set set2 = (HashSet) map.get(strLen);
                    set2.add(str);
                    map.put(strLen, set2);
                } else {
                    Set set1 = new HashSet();
                    set1.add(str);
                    map.put(strLen, set1);
                }
    
            }
            System.out.println(map.lastKey());
            System.out.println(map.get(map.lastKey()));
        }
    
        private static void printArray(Object[] currentObjArr) {
            for (Object obj : currentObjArr) {
                char str = (char) obj;
                System.out.println(str);
            }
    
        }
    
        private static String getLongestSubString(String input) {
    
            Set<Character> set = new LinkedHashSet<Character>();
            String longestString = "";
            int len = input.length();
            for (int i = 0; i < len; i++) {
                char currentChar = input.charAt(i);
                boolean isCharAdded = set.add(currentChar);
                if (isCharAdded) {
                    if (i == len - 1) {
                        String currentStr = getStringFromSet(set);
    
                        if (currentStr.length() > longestString.length()) {
                            longestString = currentStr;
                        }
                    }
                    continue;
                } else {
                    String currentStr = getStringFromSet(set);
    
                    if (currentStr.length() > longestString.length()) {
                        longestString = currentStr;
                    }
                    set = new LinkedHashSet<Character>(input.charAt(i));
                }
    
            }
    
            return longestString;
        }
    
        private static String getStringFromSet(Set<Character> set) {
    
            Object[] charArr = set.toArray();
    
            StringBuffer strBuff = new StringBuffer();
            for (Object obj : charArr) {
                strBuff.append(obj);
    
            }
    
            return strBuff.toString();
        }
    }
    
    0 讨论(0)
  • 2020-12-12 18:44

    Simple and Easy

    import java.util.Scanner;
    
    public class longestsub {
    
        static Scanner sn = new Scanner(System.in);
        static String word = sn.nextLine();
    
        public static void main(String[] args) {
            System.out.println("The Length is " +check(word));
        }
        private static int check(String word) {
            String store="";
            for (int i = 0; i < word.length(); i++) {
                if (store.indexOf(word.charAt(i))<0) {
                    store = store+word.charAt(i);
                }
            }
            System.out.println("Result word " +store);
            return store.length();
        }
    
    }
    
    0 讨论(0)
  • 2020-12-12 18:49

    Longest substring without repeating character in python

    public int lengthOfLongestSubstring(String s) {
        if(s.equals(""))
            return 0;
        String[] arr = s.split("");
        HashMap<String,Integer> map = new HashMap<>();
        Queue<String> q = new LinkedList<>();
    
        int l_till = 1;
        int l_all = 1;
        map.put(arr[0],0);
        q.add(arr[0]);
        for(int i = 1; i < s.length(); i++){
            if (map.containsKey(arr[i])) {
                if(l_till > l_all){
                    l_all = l_till;
                }
                while(!q.isEmpty() && !q.peek().equals(arr[i])){
                    map.remove(q.remove());
                }
                if(!q.isEmpty())
                   map.remove(q.remove());
                q.add(arr[i]);
                map.put(arr[i],i);
                //System.out.println(q);
                //System.out.println(map);
                l_till = q.size();
            }
            else {
                l_till = l_till + 1;
                map.put(arr[i],i);
                q.add(arr[i]);
            }
        }
        if(l_till > l_all){
                    l_all = l_till;
                }
        return l_all;
    }
    
    0 讨论(0)
  • 2020-12-12 18:50

    Algorithm in JavaScript (w/ lots of comments)..

    /**
     Given a string S find longest substring without repeating characters.
     Example:
    
     Input: "stackoverflow"
     Output: "stackoverfl"
    
     Input: "stackoverflowabcdefghijklmn"
     Output: "owabcdefghijklmn"
     */
    function findLongestNonRepeatingSubStr(input) {
        var chars = input.split('');
        var currChar;
        var str = "";
        var longestStr = "";
        var hash = {};
        for (var i = 0; i < chars.length; i++) {
            currChar = chars[i];
            if (!hash[chars[i]]) { // if hash doesn't have the char,
                str += currChar; //add it to str
            hash[chars[i]] = {index:i};//store the index of the char
        } else {// if a duplicate char found..
            //store the current longest non-repeating chars. until now
            //In case of equal-length, <= right-most str, < will result in left most str
            if(longestStr.length <= str.length) {
                longestStr = str;
            }
            //Get the previous duplicate char's index
            var prevDupeIndex = hash[currChar].index;
    
            //Find all the chars AFTER previous duplicate char and current one
            var strFromPrevDupe = input.substring(prevDupeIndex + 1, i);
            //*NEW* longest string will be chars AFTER prevDupe till current char
            str = strFromPrevDupe + currChar;
            //console.log(str);
            //Also, Reset hash to letters AFTER duplicate letter till current char
            hash = {};
            for (var j = prevDupeIndex + 1; j <= i; j++) {
                hash[input.charAt(j)] = {index:j};
            }
        }
      }
      return longestStr.length > str.length ? longestStr : str;
    }
    
    //console.log("stackoverflow => " + findLongestNonRepeatingSubStr("stackoverflow"));      
    //returns stackoverfl
    
    //console.log("stackoverflowabcdefghijklmn => " + 
    findLongestNonRepeatingSubStr("stackoverflowabcdefghijklmn")); //returns owabcdefghijklmn
    
    //console.log("1230123450101 => " + findLongestNonRepeatingSubStr("1230123450101")); //    
    returns 234501
    
    0 讨论(0)
提交回复
热议问题