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.
My train of thought:
The
starts with the start and I two variables, where start is used to indicate the position of the previous character at the beginning of the current substring, and I represents the position of the trailing character of the current substring. The array posflag is used to record the current position of the repeating character that occurred (ignoring the current character, where the current character last occurred). The main branch has two parts, the first part is the current character printable repeating character, at this time should put the character in Posflag to update, also need to record at this time the length of the legal substring is longer than the oldest string recorded, and update operations; the second part deals with repeating characters, The position of start should be moved to the last occurrence of the repeating character (but it is important to note that start can only be moved backwards, cannot move forward, this is easy to pass, so there will be a slash part of the judgment statement), and then update the character occurrence position, And compares whether the current substring is longer than the maximum substring length for the record to be updated accordingly. The code is as follows
public class Solution {public int lengthoflongestsubstring (String s) { int[] Posflag = new int[256]; for (int i = 0;i < i++) posflag[i] = 1; int start = -1,max = 0; for (int i = 0;i < S.length (); i++) { //system.out.println (int) S.charat (i)); if (posflag[(int) S.charat (i)]!=-1) { if (posflag[(int) S.charat (i)]>start) start = posflag[(int ) S.charat (i)]; posflag[(int) S.charat (i)] = i; if (i-start>max) max = I-start; } else{ posflag[(int) S.charat (i)] = i; if (i-start>max) max = I-start; } } SYSTEM.OUT.PRINTLN (max); return max;} }
Longest Substring without repeating characters