Leetcode:longest Substring without repeating characters

Source: Internet
Author: User

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "ABCABCBB" are "abc", which the length is 3. For "bbbbb" the longest substring are "B", with the length of 1.

Analysis: This topic and Minimum Substring window has the similarities, two topics are to find a special window length, Minimum Substring Window is a string containing all the characters of a minimum window, The problem is to ask for a maximum window of all characters, both of which can be solved by two pointers methods.

The two key points of this question: (1) How to extend window (2) How to narrow the window when it encounters repeating characters.

We can use an array to hold the index of the character that has already appeared, or 1 if the character does not appear, and when a repeating character is encountered, we simply move the pointer to the beginning of the window to the position where the first repeating character appears.

Time complexity is O (n), Spatial complexity O (1). The code is as follows:

classSolution { Public:    intLengthoflongestsubstring (strings) {intn =s.length (); if(n = =0)return 0; Vector<int> pos ( the, -1); intWin_start =0, Max_width =0;  for(intWin_end =0; Win_end < n; win_end++){            if(Pos[s[win_end]] = =-1){//Not repeating characterPos[s[win_end]] =Win_end; Max_width= Max (max_width, Win_end-win_start +1); }Else{//repeating character                 for(; Win_start < pos[s[win_end]; win_start++) {//eliminate characters from Win_start to Pos[s[win_end]]Pos[s[win_start]] =-1; } Win_start++; Pos[s[win_end]]=Win_end; }        }                returnMax_width; }};

Leetcode:longest Substring without repeating characters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.