3: Longest string with no repeating characters

Source: Internet
Author: User

Given a string, find the length of the oldest string that does not contain repeating characters.

Example 1:

Input : "ABCABCBB"

Output : 3

Explanation : The oldest string of non-repeating characters is "abc", with a length of 3.

Example 2:

Input : "BBBBB"

Output : 1

Main idea: "Sliding window", using a container to save the traversed characters.

Iterates through the string, saves the characters that are not duplicated in the window, adds one to the right edge of the window, and then slides one bit to the right, reducing the window size from the left edge of the window when repeating characters are encountered, until that repeating character is not included in the container. In essence, it also uses external space.

Solution 1:

intLengthoflongestsubstring (strings) {    intn =s.size (); Unordered_set<Char>Set; intMax =0, i =0, j =0;  while(I < n && J <N) {Auto F=Set. Find (S.at (j)); if(f = =Set. End ()) {            //right Border swipe right one            Set. Emplace (S.at (j + +)); Max= Std::max (max, J-i); }        Else        {            //left Border narrows right one            Set. Erase (S.at (i++)); }    }    returnMax;}

Solution 2:

intLengthoflongestsubstring (strings) {intn =s.size (); Unordered_map<Char,int>MP; intMax =0;  for(intj =0, i =0; J < N; ++j) {if(Mp.count (s.at (j)) >0)            {                //The next one that shrinks the left side of the window to duplicate characters directlyi =Std::max (mp.at (s.at (j)), I); } Max= Std::max (max, J-i +1); //right Border swipe right oneMp.emplace (S.at (j), J +1); }        returnMax; }

3: Longest string with no repeating characters

Related Article

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.