使用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
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;
- }
- }