O(n) Java solution with String


  • 0
    D
     public int lengthOfLongestSubstring(String s) {
    	if(s==null||s.equals("")){
    		return 0;
    	}
    	char[] a=s.toCharArray();
    	String b=String.valueOf(a[0]);
    	int longest=1;
    	int buffer=1;
    	for(int i=1;i<a.length;i++){
    		 if(b.indexOf(String.valueOf(a[i]))==-1){
    			 b = b+String.valueOf(a[i]);
    			 buffer++;
    			 if(buffer>=longest){
    				 longest = buffer;
    			 }
    		 }else{
    			 b = b.substring(b.indexOf(String.valueOf(a[i]))+1)+String.valueOf(a[i]);
    			 buffer = b.length();
    		 }
    		 
    	}
    	return longest;
        
    }

Log in to reply
 

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