🐌1. 题目描述

:::info 求一个字符串中,最长无重复字符子串长度。 ::: 示例

输入: s = “abcabcbb” 输出: 3 解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。

输入: s = “bbbbb” 输出: 1 解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。


💡2. 解决思路

动态滑动窗口


🚩3. 代码实现

  1. class Solution {
  2. public int lengthOfLongestSubstring(String s) {
  3. if(s == "" || s==null){
  4. return 0;
  5. }
  6. int max = 0;
  7. Set set = new HashSet<Character>();
  8. int start = 0;
  9. for(int end = 0; end < s.length(); end++){
  10. // 不满足条件
  11. while(set.contains(s.charAt(end))){
  12. set.remove(s.charAt(start));
  13. start++;
  14. }
  15. set.add(s.charAt(end));
  16. max = Math.max(end - start + 1,max);
  17. }
  18. return max;
  19. }
  20. }

🔑4. 考点