题目描述:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

输入: “abcdbef”
输出: 5
解释: 因为无重复字符的最长子串是 “cdbef”,所以其长度为 5

思路:
1.判断 重复, 利用 hashset.contains() (o(1)时间复杂度)

2.遍历采用滑动窗口的方式:找出不含重复字符的最长子串
代码:

public int lengthOfLongestSubstring(String s) {
  int i = 0, j = 0;
  int maxLength = 0;
  int n = s.length();
  
  Set set = new HashSet<Character>();
  
  while (i < n && j < n) {
   if (!set.contains(s.charAt(j))) {
    set.add(s.charAt(j++));
    maxLength = Math.max(maxLength, j - i + 1);
    
   } else {
    set.remove(i++);// 移除i对对应的元素,i向前移
    
   }
   
  }
  return maxLength;
 }

相关文章: