Leetcode problem 3.Longest Substring without repeating characters

Source: Internet
Author: User

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb" , the answer "abc" is, which the length is 3.

Given "bbbbb" , the answer "b" is, with the length of 1.

Given "pwwkew" , the answer "wke" is, with the length of 3. Note that the answer must was a substring, is "pwke" a subsequence and not a substring.

If you want to know if there are duplicate characters, you must have a record operation to scan each letter. All characters can be placed in an array, with characters as subscripts to store their last occurrence. If a character is already recorded, and the position of the character is on the right side of the left edge of the substring (with the left border), the character repeats, then the left side of the substring is re-assigned to the next position of the repeating character, which is used to remove the leftmost repeating character. The longest length of a string is updated every time a letter is scanned.

The code is as follows:

1 classSolution {2  Public:3     intLengthoflongestsubstring (strings) {4         intMax_size (0), Left_bound (0), Str_size (S.length ());5         intlast_positions[ the];6memset (Last_positions,-1,sizeof(last_positions));7 8          for(inti =0; i < str_size; ++i) {9             if(Last_positions[s[i]] >=left_bound) {TenLeft_bound = Last_positions[s[i]] +1; One             } ALast_positions[s[i]] =i; -Max_size = Max (max_size, I-left_bound +1); -         } the         returnmax_size; -     } -};

Leetcode problem 3.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.