3. Longest Substring Without Repeating Characters

    xiaoxiao2021-03-25  114

    Given a string, find the length of the longest substring without repeating characters.

    Examples:

    Given "abcabcbb", the answer is "abc", which the length is 3.

    Given "bbbbb", the answer is "b", with the length of 1.

    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    思想:滑窗思想(窗口i~j-1  ,如果新来的节点s[j]包含set中,那么窗口删除最左边的元素并且i右移)set是不包含重复元素的集合,

    public int lengthOfLongestSubstring(String s) { int len=s.length(); Set<Character> set=new HashSet(); int i=0,j=0; int max=0; while(j<len&&i<len){ Character c=s.charAt(j); if(!set.contains(c)){ set.add(c); j++; max=Math.max(max, j-i); }else{ set.remove(s.charAt(i));//如果set中含有字符c,则从头开始移除字符直到可以添加 i++; } } System.out.println(max); return max; }

    转载请注明原文地址: https://ju.6miu.com/read-10946.html

    最新回复(0)