Solution using java built in functions

  • 0
        public int lengthOfLongestSubstring(String s) {
            if(s.length() < 2){
                return s.length();
            int maxLength = 0;
            int start = 0;
            int repIndex = 0;
            for(int i = 0; i < s.length(); i++){
                repIndex = s.substring(start,i).indexOf(s.charAt(i));
                if(repIndex != -1){
                    maxLength = Math.max(maxLength,i-start);
                    start = start + repIndex + 1;
            maxLength = Math.max(maxLength,s.length()-start);
            return maxLength;

    Idea is to just iterate through the string and keep track of unique substring. I used one pointer 'start' to save starting index of the unique substring. Each time we see a char which exists in the considered unique substring at that moment, we update our maxLength with the substring length and update 'start' with a new position.

Log in to reply

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