使用hash表和双指针
- 需要两个指针,一个指向无重复节点,默认是0 。另一个节点指向从左往右迭代遍历
- 因为是子列表,所以是连续的,这个是重要信息
- hash记录字符出现的次数,没有出现就新增,长度为一
- 如果这个字符已经出现过了,并且长度不为一,就需要把它的长度减少为一,并且增加左指针对应的下标加一
- 计算左右指针的最大值加一就是我们的最终答案
-
package com.company.test.最长不含重复字符的子字符串; import java.util.HashMap; import java.util.Map; /** * @author xienl * @description 最长不含重复字符的子字符串 * @date 2022/9/15 */ public class Solution { public static void main(String[] args) { Solution solution = new Solution(); String str = "abcabcbb"; System.out.println(solution.lengthOfLongestSubstring(str)); } public int lengthOfLongestSubstring (String s) { // write code here Map<Character, Integer> map = new HashMap<>(); int res = 0; for (int i = 0, j = 0; j < s.length(); j++){ char cc = s.charAt(j); map.put(cc, map.getOrDefault(cc, 0) + 1); while (map.get(cc) > 1){ map.put(s.charAt(i), map.get(s.charAt(i++)) - 1 ); } res = Math.max(res, j - i + 1); } return res; } }