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