Leetcode:longest Substring with at the most of the Distinct characters

Source: Internet
Author: User

Given a string, find the length of the longest substring T that contains at most 2="ECE" which its LENGT H is 3.

Method One: Using HashMap, Map contains elements and their occurrences. Maintain a maximum length. With two pointers, the right hand goes all the way up to 3 dinstinct character. Then adjust the left pointer to delete the element, directly from the left to the right character by the deletion, has been deleted until a character will no longer appear. Determines whether the number of characters deleted is reduced to 0.

My method: Did not do OJ, do not know to No

1  Public classSolution {2      Public intlengthoflongestsubstringtwodistinct (String s) {3         if(s==NULL|| S.length () ==0)return0;4Hashmap<character, integer> map =NewHashmap<character, integer>();5         intLongest = 0;6         intL = 0;7         intR = 0;8          while(R <s.length ()) {9             Charc =S.charat (r);Ten             if(Map.containskey (c)) { OneMap.put (c, Map.get (c) +1); A             } -             Else { -Map.put (c, 1); the                 if(Map.size () >= 3) { -Longest = Math.max (longest, Rl); -                     CharD =S.charat (l); -                      while(Map.size () >= 3 && L <=r) { +                         if(Map.get (d) > 1) map.put (d, Map.get (d)-1); -                         ElseMap.Remove (d); +l++; A                     } at                 } -             } -r++; -         } -Longest = Math.max (longest, Rl); -         returnlongest; in     } -}

Each of these elements will enter the window once, up to the window once, so the time complexity of the split on each element is O (1), the total time complexity is O (N)

Another way online, can be deleted faster.

Turn:

The linear solution to this problem is to maintain a sliding window with a substring that contains up to two different characters. When you want to add a new character, you need to completely remove all occurrences of one of the previous characters. Here are two questions to consider:

1) in the existing two characters, how to choose to remove all occurrences of its characters?

2) How do I change the window after I have selected the removed characters?

For question 1, the character at the beginning of the window must be removed, but should you always select the character and then remove all occurrences? Taking "Abac" as an example, it can be found that when scanning to C, a is bound to be removed, but if you remove all occurrences of a, then there is only "C" left. This should be the removal of all occurrences of B, by removing the first of a, so as to get "AC." From this point of view, the selection criteria should be the last occurrence of the character position, the last occurrence of the position of the left (early), then its appearance is deleted after the decrease in the length of the less . Therefore, you should delete the last occurrence position at the leftmost character.

For question 2, because the topic stipulates that the window will have a maximum of only 2 characters, in fact, how to delete can be: the slow can be deleted from left to right, fast, you can directly let the new window to the last occurrence of the selected character position of the next character.

The following code uses a map structure to represent sliding window,key as a character, and value for the corresponding last occurrence position. In fact, you can completely avoid the use of map, because the inside of the entry up to only two, a waste of space. This is due to the subsequent extension and maintenance of the code.

In order to get the earliest characters in the last position of the map, we traverse all the entry. This is actually very inefficient, but considering that there are only 2 elements in the map, the overhead of traversal is small and negligible.

1      Public intlengthoflongestsubstringtwodistinct (String s) {2         intStart = 0;3         intMaxLen = 0;4 5         //key:letter; value:the index of the last occurrence.6Map<character, integer> map =NewHashmap<character, integer>();7         inti;8          for(i = 0; i < s.length (); + +i) {9             Charc =S.charat (i);Ten             if(map.size () = = 2 &&!Map.containskey (c)) { One                 //Pick the character with the leftmost last occurrence. A                 CharCharendsmostleft = ' '; -                 intMinlast =s.length (); -                  for(CharCh:map.keySet ()) { the                     intLast =map.get (CH); -                     if(Last <minlast) { -Minlast =Last ; -Charendsmostleft =ch; +                     } -                 } +  A Map.Remove (charendsmostleft); atStart = Minlast + 1; -             } - Map.put (c, i); -MaxLen = Math.max (maxlen, I-start + 1); -         } -         returnMaxLen; in}

Leetcode:longest Substring with at the most of the Distinct 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.