3 longest Substring without repeating characters (longest non-repeating contiguous substring medium)

Source: Internet
Author: User

In the string, the longest continuous substring is not repeated.

Idea: Use HashMap, find unordered_map faster than map, set a starting position, calculate the length, to reduce the value of the starting position

Eg:a,b,c,d,e,c,b,a,e

0 1 2) 3 4

0 1 5) 3 4

0 6 5) 3 4

7 6 5) 3 4

7 6 5 ) 3 8

When C appears again, the start value is set to Map[c]+1=3, and for the next B, because Map[b]<start, the direct map[b]=i

1 classSolution {2  Public:3     intLengthoflongestsubstring (strings) {4unordered_map<Char,int>Mymap;5         intflag=0;6         intstart=0, i=0;7unordered_map<Char,int>:: iterator ite;8          while(i<s.size ()) {9Ite=Mymap.find (S[i]);Ten             if(ite==Mymap.end ()) { Onemymap[s[i]]=i; AFlag=max (flag,i-start+1); -             } -             Else{ the                 if(mymap[s[i]]>=start) -start=mymap[s[i]]+1; -mymap[s[i]]=i; -Flag=max (flag,i-start+1); +             } -++i; +         } A         returnFlag; at     } -};

Time complexity: O (N)

Time-Out Solution:

1 classSolution {2  Public:3     intLengthoflongestsubstring (strings) {4map<Char,int>Mymap;5         intI=0, max=0, Flag;6map<Char,int>:: iterator ite;7          while(i<s.length ()) {8Ite=Mymap.find (S[i]);9             if(ite==Mymap.end ()) {Tenmymap[s[i]]=i; One                 if(Mymap.size () >max) Amax=mymap.size (); -             } -             Else{ theFlag=ite->second; - mymap.clear (); Every time it clears, it's the way it fails. -                  for(intj=flag+1; j<=i;++j) { -mymap[s[j]]=J; +                 } -             } +++i; A         } at         returnMax; -     } -};

3 longest Substring without repeating characters (longest non-repeating contiguous substring medium)

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.