Article Directory
No repeating longest substring of characters: 48 face questions
One, Title Description
Please find a longest common string does not contain repeating characters from a string, we calculate the length of the longest substring. Suppose string contains only characters from 'a' to 'z' of.
For example, the string "arabcacfr", excluding the longest substring of characters is repeated "acfr", length of 4.
Second, the problem analysis
Encounter problems, first analyze the problem, the use of the algorithm is determined by the results of the analysis.
In general, we will put pen to paper to draw on paper, a list of some of the basic situation. After the analysis of this question can be found in the relationship.
Defined function f (i) is: The maximum length of the substring in the i-th character to the end of the no repeating characters.
(1) Before the i-th character has not been seen, there are: F (i) = F (i-1) + 1'd
(2) When appeared before the i-th character, and note the location of the last character appears distance d
- If d <= f (i-1), there is f (i) = d;
- If d> f (i-1), there is f (i) = f (i-1) +1;
Traverse can start from the first character, and define two int variables preLength curLength to represent the f (i-1) and f (i), and creates an array of length pos 26 to store the 26 letters of the last occurrence position, to solve the above description.
Third, the problem is solved
public int maxLength(String str) {
if(str==null || str.length()<=0) {
return 0;
}
// 即f(i-1)
int preLength=0;
// 即f(i)
int curLength;
int maxLength=0;
// 用于存放字母上次出现的位置
int[] pos= new int[26];
Arrays.fill(pos, 0);
for(int i=0;i<str.length();i++) {
int letterNumber = str.charAt(i)-'a';
if(pos[letterNumber]<0 || i-pos[letterNumber]>preLength) {
curLength=preLength + 1;
} else {
curLength=i-pos[letterNumber];
}
pos[letterNumber]=i;
if(curLength>maxLength) {
maxLength=curLength;
}
preLength=curLength;
}
return maxLength;
}