Share my java solution


  • 0
    M
    1. use an array as a map (7ms)

       public int lengthOfLongestSubstring(String s) {
       char[] sc = s.toCharArray();
       int[] map = new int[256];
       Arrays.fill(map,-1);
       
       int max = 0, start=0;
       for(int i=0;i<=sc.length;i++){
           if(i==sc.length){
               max = Math.max(max, i-start);
               break;
           }
           int index = map[sc[i]];
           if(index>=0){
               max   = Math.max(max, i - start);
               start = Math.max(start,index+1);
           }
           map[sc[i]] = i;
       }
       return max; }
      
    2. Use a HashMap (18ms)

       public int lengthOfLongestSubstring(String s) {
       char[] sc = s.toCharArray();
       HashMap<Character, Integer> map = new HashMap<>();
       int max = 0, start=0;
       for(int i=0;i<=sc.length;i++){
           if(i==sc.length){
               max = Math.max(max, i-start);
               break;
           }
           int index = map.getOrDefault(sc[i],-1);
           if(index<0){
               map.put(sc[i],i);
           }else{
               max = Math.max(max, i - start);
               start = Math.max(start,index+1);
               map.put(sc[i],i);
           }
       }
       return max;
      

      }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.