Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
Solution:
public class Solution { public int lengthOfLongestSubstring(String s) { int maxLen = 0; if(s.length() == 1) return 1; else { int l = 0; int r = 0; int[] set = new int[256]; Arrays.fill(set,-1); for(int i = 0; i < s.length(); i++){ int len = 0; if(-1 == set[s.charAt(i)] || set[s.charAt(i)] < l){ r = i; len = r -l+1; set[s.charAt(i)] = i; }else { l = set[s.charAt(i)] + 1; r = i; set[s.charAt(i)] = i; } maxLen = Math.max(maxLen,len); } return maxLen; } } }