My short accepted Java Solution


  • 0
    S

    Uses a map but you could also use a int array with the idx being the char offset from 'a'

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
    
            if (s.length()<=1) return s.length();
            Map<Character,Integer> seen=new HashMap<Character,Integer>();
            char[] c = s.toCharArray();
            int max=0;
            int lastMax=0;
            for(int i = 0 ; i < c.length   ; i++)  {
                char v = c[i];
                if (seen.containsKey(v)) {
                    int pos = seen.get(v);
                    if (pos>=lastMax) {
                        int size = i - lastMax;
                        if (size>max) {
                            max=size;
                        }
                        lastMax=pos+1;
                    }
                }
                seen.put(v,i);
            }
            int pos = c.length; 
            int size = pos - lastMax;
            if (size>max) {
                max=size;
            }
            return max;
        }
    }

Log in to reply
 

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