给定字符串,返回最长不重复子串的长度
比如:
输入"abcaf",返回4,代表子串"bcaf"
输入"abccf",返回3,代表子串"abc"
思路:
通过set记录遍历过的元素
import java.util.*;
public class Main {
public static void main(String[] args) {
String s = "abccf";
System.out.println(maxLength(s));
}
public static int maxLength(String s) {
if (s == null || s.length() < 1) {
return 0;
}
Set<Character> set = new HashSet<>();
int right = 0;
int res = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
if (i != 0) {
//移除前一位的元素
set.remove(s.charAt(i-1));
}
//防止越界并且从right判断,减少之前的重复判断
while (right < n && !set.contains(s.charAt(right))) {
set.add(s.charAt(right));
right++;
}
res = max(res, right - i);
}
return res;
}
public static int max(int a, int b) {
return a > b ? a : b;
}
}