A sliding window is an abstract concept commonly used in array/string problems. A sliding window is a window "slides" its two boundaries to the certain direction. For example, if we slide [i, j)[i,j) to the right by 11 element, then it becomes [i+1, j+1)[i+1,j+1) (left-closed, right-open).
Here is my solution without any hashset or hashmap
public int lengthOfLongestSubstring(String s) {
int result=0;
String sub="",buf="";
char[] array=s.toCharArray();
for(int i=0;i<array.length;i++){
if(sub.indexOf(array[i])!=-1){
//记录每一次的当前最长串的长度
// if(buf.length()<sub.length()) buf=sub;
sub=sub.substring(sub.indexOf(array[i])+1);
}
sub+=array[i];
result=Math.max(sub.length(),result);
}
return result;
}
but at first,I did a mistake .Although I want to save the longest substring every time, I am not sure which is the longest.
That is the problem,but actually, it is simple-----just set the current substring is the longest, and compare the next one to get the longest.
But we should notice the string operation will be spent so much time.---Runtime: 65 ms
So here is the official approchHashMap--Runtime: 54 ms
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
ans = Math.max(ans, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return ans;
}
1044



被折叠的 条评论
为什么被折叠?



