Easy understand java solution


  • 2
    D

    public class Solution {
    public int lengthOfLongestSubstring(String s) {

       if(s.length()<2) return s.length(); 
       Map <Character, Integer> hash = new HashMap();
       int length=s.length();
       int max=1,end = 1,start = 0;
       
       hash.put(s.charAt(0),0);
       while(end<length){
         if(hash.containsKey(s.charAt(end))&&hash.get(s.charAt(end))>=start){
             //s.charAt(end))>=start keep start not backforward
             //or abba=3
             start = hash.get(s.charAt(end))+1;
         }
         max = Math.max(max,end-start+1);
         hash.put(s.charAt(end),end);
         end++; 
       } 
       return max;
    }
    

    }


  • 0
    F

    Hi , I think my codes is same with yours, but it told me "Time Limit Exceeded" ~

    public int lengthOfLongestSubstring(String s) {
        if (s == null) return 0;
        if (s.length() < 2) return s.length();
        Map<Character, Integer> hash = new HashMap();
        int length = s.length();
        int max = 0, end = 0, start = 0;
        for (;end < length; end++ ){
            if (hash.containsKey(s.charAt(end)) && hash.get(s.charAt(end)) >= start){
                start = hash.get(s.charAt(end)) + 1;
            }
            hash.put(s.charAt(end),end);
            max = Math.max(max , end-start+1);
        }
        return max;
    }

Log in to reply
 

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