题目描述:请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
思路:
代码:
1)手写代码:
class Solution {
public int lengthOfLongestSubstring(String s) {
//每次记录个最大值,对比留最大
int i = 0;
Queue<Character> queue = new LinkedList<>();//记录最大字串
Set<Character> set = new HashSet<>();//判断是否已经包含
char[] ch = s.toCharArray();
for(char c : ch){
if(!set.contains(c)){//不包含就添加
set.add(c);
queue.add(c);
}else if(set.contains(c)){//出现包含,就先得到最大值
i = Math.max(queue.size(),i);
while(!(c == queue.peek())){//循环弹出包含的字符之前的内容,同时要从set中remove;
set.remove(queue.poll());
}
queue.add(c);
queue.poll();
}
}
return Math.max(i,queue.size());
}
}
2)答案代码: