Given a string, find the length of the oldest string that does not contain duplicate characters.
Example:
Given "ABCABCBB", the oldest string without repeated characters is "abc", then the length is 3.
Given "BBBBB", the longest substring is "B", the length is 1.
Given "Pwwkew", the eldest son string is "Wke", and the length is 3. Note that the answer must be a substring, and "Pwke" is a subsequence rather than a substring.
In fact, this problem is very simple, but also because of their own foundation is relatively poor, Ali side on the hang on this topic, think oneself really too low. The main reason is that I do not know some basic methods or attributes of Java (many of them are reasons)
(not sure if this is optimal, followed by a set for optimization)
This defines a variable first, which is used to represent the number one character of the current substring, where count is counted, and Max goes to count the current maximum length. Index represents the current character and determines whether he or she is repeating a substring.
Class Solution {
public int lengthoflongestsubstring (String s) {
int len = S.length ();
int max = 0;
int count = 1;
int-i = 0;
if (len==1)
return 1;
for (int i =1;i<len;i++) {
char ch = s.charat (i);
int index = S.indexof (Ch,first);
if (index==i) {//To determine if the current character is a duplicate character with the current substring, this situation is not duplicated
count++;
max = Math.max (count, Max);
}
else{//This case is a duplicate substring, which will be counted again from the next character of the repeated character, count to 1
max = Math.max (count, Max);
Count = 1;
i = index+1;
i = A;
}
}
return Max;
}
}
Optimization: Using the sliding window method to optimize, J constantly add to it, when J has a repeat, I delete an element, and then iterate.
(In fact, you can still continue to optimize, that is, delete the repeat position and repeat all the characters before, move I to the next position of the repeating character)
Class Solution {
public int lengthoflongestsubstring (String s) {
int Le n = s.length ();
int Max =0;
Set<character> ch = new hashset<character> ();
for (int i =0,j=0;i<len&&j<len;) {
if (!ch.contains (S.charat (j))) {
Ch.add (S.charat (j));
j + +;
max = Math.max (max, j-i);
}
else{
Ch.remove (S.charat (i));
i++;
}
}
return to Max;
}
}