[Leetcode] Longest Substring without repeating characters longest non-repeating substring

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 problem of finding the longest non-repeating substring is similar to the previous isomorphic Strings isomorphic string, and we are creating an integer array of 256-bit size instead of a hash table, because the ASCII tables are capable of representing 256 characters, so all the characters can be recorded. Then we need to define two variables, res and left, where Res is used to record the length of the longest no-repeat substring, where it points to the start of the leftmost substring, and then we traverse the entire string, for each character traversed, if the string in the hash table corresponds to a value of 0, The description did not encounter the character, then the longest non-repeating substring is calculated, I-left +1, where I is the longest non-repeating substring rightmost position, left is the leftmost position, there is also a case to calculate the longest non-repeating substring, that is, when the value in the hash table is less than left, This is because duplicate characters appear at this point, the left position is updated, and if new characters are encountered, the longest non-repeating substring will be recalculated. Finally, each time you assign the value of the current character to I+1 in the Hashtable. The code is as follows:

classSolution { Public:    intLengthoflongestsubstring (strings) {intm[ the] = {0}, res =0, left =0;  for(inti =0; I < s.size (); ++i) {if(M[s[i]] = =0|| M[s[i]] <Left ) {Res= Max (res, I-left +1); } Else{ Left=M[s[i]]; } M[s[i]]= i +1; }        returnRes; }};

[Leetcode] Longest Substring without repeating characters longest non-repeating substring

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.