请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
- 双指针法
public class Solution {
public static int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int result = 0, i = 0, j = 0;
while (i < n && j < n) {
//charAt:返回指定位置处的字符
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j));
j++;
result = Math.max(result, j - i);
}
else {
set.remove(s.charAt(i));
i++; }
}
return result;
}
}