Sliding Window Java solution


  • 0
    M
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if(s.length()==0||s==null){
                return 0;
            }
            int count=1;
            int i=1, max=1;
            Map<Character,Integer> map=new HashMap<Character,Integer>();
            map.put(s.charAt(0),0);
            int left=0;
            while(i<s.length()){
                if(map.containsKey(s.charAt(i))){
                    int nextPos=map.get(s.charAt(i));
                    while(left<=nextPos){
                        map.remove(s.charAt(left));
                        left++;
                    }
                    left=nextPos+1;
                    count=i-nextPos;
                    map.put(s.charAt(i),i);
                }else{
                    map.put(s.charAt(i),i);
                    count++;
                    if(count>max){
                        max=count;
                    }
                }
                i++;
                
            }
            return max;
            
        }
    }
    

Log in to reply
 

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