Simple solution without additional data structure


  • 0
    N
    public int lengthOfLongestSubstring(String s) {
        
        int longestSubLeng = 0;
        String longestSubString = "";
      
        for(int i=0; i<s.length(); i++){
            if(longestSubString.indexOf(s.charAt(i)) == -1){ //not in string yet
                longestSubString += s.charAt(i);
            }else{
                if(longestSubString.length()>longestSubLeng){
                    longestSubLeng = longestSubString.length();
                }
                int index = longestSubString.indexOf(s.charAt(i)); //find where to start the new substring
                longestSubString = longestSubString.substring(index+1,longestSubString.length()) + s.charAt(i);      
            }
        }
        return longestSubString.length() > longestSubLeng ? longestSubString.length() : longestSubLeng ;
    }

Log in to reply
 

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