Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
Subscribe to see which companies asked this question.
public static void main(String[] args) {
System.out.println(lengthOfLongestSubstring("acbdbefdc"));
}
public class Solution3 {
public static int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) return 0;
int len = s.length();
if (len == 1) return 1;
HashSet<Character> set = new HashSet<Character>();
int i, j = 0, maxLen = 0;
for ( i = 0; i < len; i++ ) {
char currentChar = s.charAt(i);
if ( set.contains(currentChar) ) {
maxLen = Math.max(maxLen, i-j);
//把之前所有与当前不等的都删掉,直到与当前值相等的,并且不把当前值存入到set中
while ( s.charAt(j) != s.charAt(i) ){
set.remove(s.charAt(j));
j++;
}
//重复值本身算了两次,所以要再加一次1
j++;
}
else set.add(currentChar);
}
return Math.max(maxLen, i-j);
}
}