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.
sliding window的思路,很多substring类问题,尤其substring需要满足某一条件的都适用这种思路。同理continuous array也是一样。
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0)
return 0;
Set<Character> record = new HashSet<>();
int rightPosition = 0;
int leftPosition = 0;
int maxLength = 0;
while(rightPosition < s.length()){
Character currentChar = s.charAt(rightPosition);
if(!record.contains(currentChar)){
record.add(currentChar);
rightPosition++;
maxLength = Integer.max(rightPosition - leftPosition, maxLength);
}
else{
record.remove(s.charAt(leftPosition));
leftPosition++;
}
}
return maxLength;
}
}