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

示例 1:

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

示例 2:

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

示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters

思路:通过滑动窗口的思想实现

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int ans  = 0;
        int i= 0;
        int j = 0;
        while( i < n && j < n){
            if(!set.contains(s.charAt(j))){//contains判断是否在集合中
                set.add(s.charAt(j++));//如果不存在,就加入,j++
                ans = Math.max(ans,j-i);//比较最大长度
            }
            else{
                set.remove(s.charAt(i++));//如果存在 i++;
            }
        }
        return ans;
    } 
}

相关文章:

  • 2021-07-23
  • 2022-01-03
  • 2021-05-17
  • 2021-12-24
  • 2021-06-12
  • 2022-01-13
  • 2021-11-15
猜你喜欢
  • 2021-06-24
  • 2021-07-22
  • 2022-12-23
  • 2021-11-30
  • 2021-06-03
  • 2021-10-17
  • 2021-11-16
相关资源
相似解决方案