public int longestSubStr(String str) {
int max = 0;
Deque<Character> deque = new ArrayDeque<>();
for (int i = 0; i < str.length(); i++) {
if (!deque.contains(str.charAt(i))) {
deque.addLast(str.charAt(i));
} else {
max = Math.max(max, deque.size());
while (deque.peek() != str.charAt(i)) {
deque.removeFirst();
}
deque.removeFirst();
deque.addLast(str.charAt(i));
}
}
max = Math.max(max, deque.size());
return max;
}
实现方案2:
// 不含重复字符的最大子串
public static int noRepeatStr(String s) {
int maxLen = 0;
int left = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
left = Math.max(left, map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i), i);
maxLen = Math.max(maxLen, i - left + 1);
}
return maxLen;
}