[C + +] leetcode:105 longest Substring without repeating characters

Source: Internet
Author: User

Topic:

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.

idea: Let's analyze the problem first, we need to find the oldest string in a string that is not duplicated. Take a look at the image analysis.

because it is a character store, you can use a special array to store the position of each character in the string. This method is common to string problems, because the character essence is a unique number, creating an array,vector<int> bitmap (256,-1); The array subscript represents the ASCII code for this character, and the element represents the position in the string. For example, the ASCII code of Q is 113, and the coordinate in the string is 0, then stored in bitmap[112] = 0.

Solved the problem of finding, now we need to consider how we can operate after we encounter repeating characters. When we encounter a character that repeats before (the previous occurrence is Occur1, this time for occur 2), we need to do a few things first to calculate the length of the currently maintained non-repeating string = Current position -Start (start indicates a flag bit, Represents the starting position of a substring that is not currently duplicated. ), and after comparison maintains a global longest non-repeating substring length ret; In the second step we need to update the next scan starting point for the first repetition of the character occur 1, and we also need to clear the coordinates of the Laststart to new start in the hash table, reset-1. Continue scanning know to find the same character again, and the same processing as before, note that after all the string is processed, it is also important to determine whether the end of the non-repeating substring is the longest "easy to ignore."


Complexity: Worst case, traverse two times string, O (N)

Answer 1:

Attention:

1. Note that the last non-repeating substring at the end is the longest, because it is not judged in the loop.

The last substring is not updated to RET and needs to be judged by        ret = max (ret, (int) s.size ()-start);
2. String.size () typeStd::basic_string<char>::size_type,Forced type conversions are required.

RET = max (ret, s.size ()-start);
Line 28:no matching function for call to ' Max (Int&, Std::basic_string<char>::size_type) '
3. Use vector<256, -1> to maintain an ASCII lookup array, this method is very good, also commonly used, need to remember.
Vector<int> bitmap (1);    Each char of S can represent an ASC code, and an array can be used to mimic the ASC code
AC Code:

Class Solution {public:    int lengthoflongestsubstring (string s) {        vector<int> bitmap (1);    Each char of S can represent an ASC code, which can be modeled with an ASC code        int ret = 0;        int start = 0;        int laststart = 0;                for (int i = 0; i < s.size (); i++)        {            //description s[i] appears in the currently maintained substring            if (bitmap[s[i]!! = 1)            {                // I-start represents the length of the substring now maintained, maintaining a longest ret                ret = max (ret, i-start);                Laststart = start;                Start = Bitmap[s[i]] + 1; The new start starts with the next coordinate of the last repeating letter                //condition Laststart to the letter between start of the coordinate for                (int j = Laststart; J < start; J + +)                {                    Bitmap[s[j]] =-1;                }            }            Bitmap[s[i]] = i; If there is no repetition, adding index to bitmap        }                //Last substring is not updated to RET, you need to judge        ret = max (ret, (int) s.size ()-start);        return ret;    }};

Answer 2: A more concise approach

idea: The idea of solving problems is the same as above, but through ingenious design, avoid a lot of operation. We maintain two variables, one is the length of the oldest string longest, and the other is the starting position of the current substring, the coordinate m.

  • m = max (charindex[s[i]]+1, m); If this character is not present, charindex[s[i]]+1 is 0 and does not affect the value of m; if so,charindex[s[i]]+1 represents the position coordinates of the last occurrence of the character moved backward one bit, updated M. Adjusts the starting position of the next search substring. This step avoids the above solution will laststart to start reset-1 operation, if the string: Q P x r j x p ... When we calculate to X, the M is 3, and the next check table although charindex[' P ' is present and equal to 1, but this coordinate must be less than charindex[' X ']+1 (which is the m=3 of the previous step), so there is no need to worry about the subsequent repetition affecting the starting position of the substring m. That is to say, the coordinates of the subsequent position must be before M. M takes max without effect.
  • Charindex[s[i]] = i; Constantly updating the ASCII table, where the element is the coordinate of the string (if there is a repetition, update to the nearest left coordinate from the current position).
  • longest =max (longest, i-m+1); maintains the length of the oldest string, I is the current position, and M is the starting position.
AC Code:
Class Solution {public:    int lengthoflongestsubstring (string s) {        vector<int> charIndex (1);        int longest = 0;        int m = 0;                for (int i = 0; i < s.size (); i++)        {            m = max (charindex[s[i]]+1, m);            Charindex[s[i]] = i;            Longest =max (longest, i-m+1);        }                return longest;}    ;



[C + +] leetcode:105 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.