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.

The solution of the string s is scanned only once, that is, the time complexity is O (n), the code is as follows:

 Public classSolution { Public intlengthoflongestsubstring (String s) {intStart = 0; Map<Character,Integer> map =NewHashmap<character,integer>(); intMax_length = 0; intSize = S.length ();//string Length         for(inti=0;i<size;i++) {            Charc =S.charat (i); if(Map.containskey (c)) {intSub_length = istart; Max_length= Sub_length>max_length?sub_length:max_length; intindex = Map.get (S.charat (i));//the position of C has occurred before//Remove start to index all characters from map                 for(intj=start;j<=index;j++) {Map.Remove (S.charat (j));                } map.put (C,i); Start= index+1;//Update Start            }            Else{map.put (c,i); if(i==size-1) Max_length = Map.size () >max_length?map.size (): max_length; }        }        returnmax_length; }}

The question is how to determine whether the current character has occurred in a string in a constant time, and a hashmap must be used. Using the Contains method of the string directly results in inefficient, limit time exceed.

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.