Find longest substring without repeating characters

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

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

Example:

Input:

30条回答
  •  长情又很酷
    2020-12-12 19:04

    Question: Find the longest substring without repeating characters. Example 1 :

        import java.util.LinkedHashMap;
        import java.util.Map;
    
        public class example1 {
    
            public static void main(String[] args) {
                String a = "abcabcbb";
                   // output => 3
                System.out.println( lengthOfLongestSubstring(a));
    
            }
    
            private static int lengthOfLongestSubstring(String a) {
                   if(a == null  || a.length() == 0) {return  0 ;}  
                   int res = 0 ;
                Map map = new LinkedHashMap<>();
                  for (int i = 0; i < a.length(); i++) {
                      char ch = a.charAt(i);
                    if (!map.containsKey(ch)) {
           //If ch is not present in map, adding ch into map along with its position
                        map.put(ch, i);
    
                    }else {
    /*
    If char ch is present in Map, reposition the cursor i to the position of ch and clear the Map.
    */ 
                        i = map.put(ch, i);// updation of index
                         map.clear();
                    }//else
    
                    res = Math.max(res, map.size());
    
                }
    
    
    
                return res;
            }
    
        }
    

    if you want the longest string without the repeating characters as output then do this inside the for loop:

    String res ="";// global
        int len = 0 ;//global
     if(len < map.size()) {
         len = map.size();
        res = map.keySet().toString();
     }
    System.out.println("len -> " + len);
    System.out.println("res => " + res);
    

提交回复
热议问题