My Java Solution O(N) time


  • 0

    Hint: The scope of possible characters in the input String is larger then just lower case letters of the alphabet.

    public class RepeatedCharsSvc {
        public int lengthOfLongestSubstring(String s) {
            
            if(s==null||s.length()==0)
            {
                return 0;
            }
            
            int[] letters=new int[128];
            for(int i=0;i<letters.length;i++)
            {
                letters[i]=-1;
            }
            int start=0;
           int maxLen=0;
            
            for(int i=0;i<s.length();i++)
            {
              int idx=(int)s.charAt(i)-0;
              if(letters[idx]!=-1)
              {
                  start=letters[idx]+1;
                  resetArray(letters,start-1);
                  
              }
              letters[idx]=i;
             
                  maxLen=Math.max(maxLen,(i-start)+1);
              
              
            }
            return maxLen;
            
            
            
        }
        
        private void resetArray(int[] arr,int index)
        {
            for(int i=0;i<arr.length;i++)
            {
                if(arr[i]<=index)
                {
                    arr[i]=-1;
                }
            }
        }
    }

Log in to reply
 

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