题目描述
思路:hash表+双指针
hash表用来判断一个字符是否存在过
双指针,左指针控制字符串不重复,右指针用于遍历字符串
实现
拿到一个数(右指针的遍历),
判断其是否存在于hash表中,如果存在就左指针开始移动,直到其不存在,
将右指针的值放入hash表中,
每次循环都计算一次长度,和最大长度做比较,循环结束后返回最大长度
class Solution {
public int lengthOfLongestSubstring(String s) {
//hash表,判断是否存在
//双指针
// 右指针拿到一个数后,判断是否存在与hash表中,
// 存在就左指针开始遍历,直到左指针和右指针的数相同,此时左指针++
//每一次都进行一个长度判断,最后返回maxlength
//长度
int maxlength=0;
//hash表,判断是否存在
Set<Character> set = new HashSet<>();
//遍历
for(int i=0,l=0;i<s.length();i++)
{
char c = s.charAt(i);
//判断是否存在,存在就一直删,直到不存在再放入
while(set.contains(c))
{
//从左边删
set.remove(s.charAt(l++));
// 为什么l不从0开始
// l 是s的索引,不是set的索引
}
set.add(c);
maxlength = Math.max(maxlength,i-l+1);
}
return maxlength;
}
}
相关知识点总结
1.Set<Character> set = new HashSet<>();
set 是一个集合类。 set继承自collection的接口类,set中只存储key
特点:
1.不能出现重复数据
2.可以出现空数据
3.数据是无序的,即不能遍历访问
相关的使用
1.声明
Set<Integer> set = new HashSet<>();
类型是int
名字是set
2.添加元素
set.add(1);
int a = 0;
set.add(a);
3.判断一个元素是否存在容器中
set.contains()
int a=0;
set.contains(a);
存在返回true,不存在返回false
4.删除元素
set.remove();
set.remove(1);
直接从set中删除1
5.输出
//直接输出
System.out.println(set);
//遍历输出
Iterator<Integer> it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
执行结果