Leetcode每日一题(2)

    科技2023-10-13  105

    题目: 无重复字符的最长子串 给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。 用滑动窗口法求解

    class Solution{ public int lengthOfLongestSubstring(String s){ int len = s.length(); int res = 0;//记录最长字符串的长度 int start = 0,end=0;//记录滑动窗口的起始和中止位置 Set<Character>set = new HashSet<>();//用set集合来防止重复 while(start<len&&end<len){ //如果窗口中包括重复元素的话,start要加一(缩小窗口),同时Set中的那个字符要移走 if(set.contains(s.charAt(end))){ set.remove(s.charAt(end)); start++; }else{ //如果窗口中没有这个新元素的话,end加一,元素长度加一,把这个字符串放到set中 set.add(s.charAt(end)); end++; res=Math.max(res,end-start); } } return res; } }
    Processed: 0.017, SQL: 8