What is a Sliding Windows?
Sliding Windows actually is a range(consist of successive elements) within a array or string. Which have a “startIndex” and “endindex” to record the position of the Sliding Windows.
How Sliding Windows applied in this problem?
Generally, we use the sliding windows to contain the substring during the iterating course with an assistant int[128] array to record the data that to sliding/moving the windows needed. The main idea is
1. let the right side of the sliding windows interate the whole string.
2. in each interating course, store the index of current char in that intarray(the ascii value of the char can be used as index of thechar in that array).
2.1 if we found that the right side of the windows meet a char that has appeared before(assume it’s ‘a’), let the left side of the windows slid to the the the next position(startIndex = array[‘a’])of the lastest ‘a’.
2.2 Then upadate the newest position data of ‘a’(where end meet it) to int array.
2.3 Check if we get a longer string(see if maxLength less than endindex - startIndex + 1).
3. Finally, when the end equal the index of the last char, the loop is over.
A great solution(using the idea of Sliding Windows)
public static int findTheLongestLengthofNonrepeatedSubString(String s){
int[] status = new int[256];
int start, end, length, strLen;
start = end = 0;
strLen = s.length();
length = 0;
while(end != strLen){
int index = (int)s.charAt(end);
start = (start < status[index] ? status[index] : start);
status[index] = end + 1;
length = length < end - start + 1 ? end - start + 1 : length;
end++;
}
return length;
}
What problems I’ve found via the sovling course of this problem?
-
Too careless and not prudent:did not found the first of my solution has a fatal flaw.
-
When there’s no train of thought temporarily or suddenly found that the problem is more complex than you have thought, don’t give up quickly(or just think that’s too hard to realize), actually, the solution maybe not faraway from my previous wrong version.
-
When I want to optimize my solution(in space or time complexity), try to start from extending my current solution (Like this time, I should have knew that int array could not only preserve the states(0 or 1), but also could store the position data!)