
方法一:
java
class Solution {
public int lengthOfLongestSubstring(String s) {
//记录当前有哪些字符
Set<Character> windoeSet = new HashSet<>();
int left = 0;
//最大长度
int maxLength = 0;
//挨个遍历
for(int right = 0;right < s.length();right++){
//用于存放
char incomingChar = s.charAt(right);
while(windoeSet.contains(incomingChar)){
//用于删除
char outcomingChar = s.charAt(left);
windoeSet.remove(outcomingChar);
left++;
}
windoeSet.add(incomingChar);
maxLength = Math.max(maxLength,right - left + 1);
}
return maxLength;
}
}
方法二:
java
class Solution {
public int lengthOfLongestSubstring(String s) {
//记录每个字符上次出现的位置
int[] indexMap = new int[128];
int left = 0;
int maxLength = 0;
for(int right = 0;right < s.length();right++){
//获取当前字符的ASCII码(Java里的char可以直接当作int用)
char c = s.charAt(right);
//查这个字符上次出现的位置
//没出现过,indexMap[c]就是0,Math.max会让left保持原地不变
//出现过,left直接到它上次出现的下一个位置(不能往回退)
left = Math.max(left,indexMap[c]);
maxLength = Math.max(maxLength,right - left +1);
//存位置时,将位置+1
indexMap[c] = right + 1;
}
return maxLength;
}
}
时间:
第二种方法少一个while循环;相对于第一种的HashSet,第二种使用数组,时间提升;
第一段的remove产生内存垃圾,Java的垃圾回收器清理他们,拖慢时间
空间:
第一种使用Character涉及到对象,吃内存;而第二种只使用数组