publicstaticintlengthOfLongestSubstring(String s){
if (s == null || "".equals(s)) {
return0;
}
int n = s.length();
Set<Character> set = new HashSet<>();
int maxLength = 0;
int i = 0;
int j = 0;
while (i < n && j < n) {
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j++));
maxLength = Math.max(j - i, maxLength);
} else {
set.remove(s.charAt(i++));
}
}
return maxLength;
}
publicstaticintlengthOfLongestSubstring(String s){
if (s == null || "".equals(s)) {
return0;
}
int n = s.length();
Map<Character, Integer> map = new HashMap<>(16);
int maxLength = 0;
for (int i = 0,j = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
maxLength = Math.max(maxLength, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return maxLength;
}
2.3 思路三:使用列表List存储不重复字符
依次遍历字符串 s 中的每次字符,若不是重复字符,加入一个列表list中,若是重复字符,则删除列表list中该重复字符以及前面的所有字符,然后再将该重复字符加入此列表list中。
在遍历的过程中统计出列表list中存储的最大字符个数,即为字符串 s 中不含重复字符的最长子串的长度。
代码实现
publicstaticintlengthOfLongestSubstring(String s){
if (s == null || "".equals(s)) {
return0;
}
List<Character> list = new ArrayList<>();
int n = s.length();
int maxLength = 0;
for (int i = 0; i < n; i++) {
int index = list.indexOf(s.charAt(i));
if (index == -1) {
list.add(s.charAt(i));
maxLength = Math.max(list.size(), maxLength);
} else {
for (int j = index; j >= 0; j--) {
list.remove(j);
}
list.add(s.charAt(i));
}
}
return maxLength;
}