Subjects brushed chicken dish algorithm longest length of the substring

Small brush algorithm garbage problem

I have absolutely no water in [blog]
buckle force string type questions

Given a string, you find out which does not contain a sub-length of the longest string of repeated characters.
Such as: Input: "abcabcbb"
Output: 3
Explanation: Because the longest substring of characters without repetition is "abc", so its length is 3.

Ideas:
traversal is impossible to traverse, the complexity is too large, the system does not give too.
I borrow a sliding window thinking.
When the window does not include a character when
Here Insert Picture Description
the window is moved back and compare the current length and maximum length
when when the next window contains a character
Here Insert Picture Description
one by one looking forward, until the same character deleted.
Here Insert Picture Description
so, I do not think then advanced to understand.
Code as follows:

// An highlighted block
class Solution {
    public int lengthOfLongestSubstring(String s) 
    {
     int num = s.length();
     Set<Character> set = new HashSet<>();
     int ans = 0;
     int i = 0;
     int j = 0;
     while(j < num && i < num)
     {
         if(!set.contains(s.charAt(j)))
         {
             set.add(s.charAt(j++));
             ans = Math.max(j-i,ans);
         }
         else
         {
             set.remove(s.charAt(i++));
         }
     }     
    return ans;
    }

Original title link: [link] https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
Lee West by the Yellow Crane Tower, the fireworks in Yangzhou.

Published an original article · won praise 0 · Views 20

Guess you like

Origin blog.csdn.net/Hannle/article/details/103975506