|
| 1 | +packagecom.yeahqing.medium._003; |
| 2 | + |
| 3 | +importjava.util.HashSet; |
| 4 | + |
| 5 | +/** |
| 6 | + * @author YeahQing |
| 7 | + * @date 2022/10/1 |
| 8 | + */ |
| 9 | +classSolution { |
| 10 | +/*** |
| 11 | + * 3. 无重复字符的最长子串 |
| 12 | + * 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。 |
| 13 | + * @param s 字符串s |
| 14 | + * @return 无重复字符的最长子串的长度 |
| 15 | + */ |
| 16 | +publicintlengthOfLongestSubstring(Strings) { |
| 17 | +// 用数据结构HashSet集合,实现控制元素只能出现一次 |
| 18 | +HashSet<Character>set =newHashSet<>(); |
| 19 | +intj = -1,ans =0; |
| 20 | +intn =s.length(); |
| 21 | +for (inti =0;i <n;i++) { |
| 22 | +if (i !=0) { |
| 23 | +// 移除集合中前一个元素, 因为判断的是i开始的子串 |
| 24 | +set.remove(s.charAt(i-1)); |
| 25 | + } |
| 26 | +// 从i+1到j可以保证没有重复的字符, 因此不需要每次重置j的位置 |
| 27 | +while (j+1 <n && !set.contains(s.charAt(j+1))) { |
| 28 | +// 如果集合中没有这个字符,就把它加入到集合中 |
| 29 | +set.add(s.charAt(j+1)); |
| 30 | +j++; |
| 31 | + } |
| 32 | +// 当前集合的长度就是当前子串中不重复的最大子串长度 |
| 33 | +// j - i + 1 |
| 34 | +ans =Math.max(ans,set.size()); |
| 35 | + } |
| 36 | +returnans; |
| 37 | + } |
| 38 | +} |