Simple iterative Java solution (ACCEPTED at 440ms)


  • 1
    A
    public static int lengthOfLongestSubstring2(String s) {
    	if (s.length() == 0)
    		return 0;
    
    	int longest = 1;
    	String sub = "" + s.charAt(0);
    
    	for (int end = 1; end < s.length(); end++) {
    		int index = sub.indexOf(s.charAt(end));
    		if (index != -1) {
    			longest = (sub.length() > longest) ? sub.length() : longest;
    			sub = sub.substring(index + 1, sub.length());
    		}
    		sub += s.charAt(end);
    	}
    	longest = (sub.length() > longest) ? sub.length() : longest;
    	return longest;
    }

Log in to reply
 

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