
滑动窗口+数组
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] last = new int[128];
for(int i=0;i<128;i++){
last[i] = -1;
}
int res = 0;
int start = 0;
for(int i=0;i<s.length();i++){
int index = s.charAt(i);
start = Math.max(start,last[index]+1);
res = Math.max(res,i-start+1);
last[index] = i;
}
return res;
}
}
动态规划+哈希表
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character,Integer> hsp = new HashMap<>();
int res = 0,temp = 0;
for(int i=0;i<s.length();i++){
int m = hsp.getOrDefault(s.charAt(i),-1);
hsp.put(s.charAt(i),i);
if(i-m>temp){
temp++;
}
else{
temp = i - m;
}
res = Math.max(res,temp);
}
return res;
}
}
动态规划+线性遍历
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> dic = new HashMap<>();
int res = 0, tmp = 0;
for(int j = 0; j < s.length(); j++) {
int i = j - 1;
while(i >= 0 && s.charAt(i) != s.charAt(j)) i--;
tmp = tmp < j - i ? tmp + 1 : j - i;
res = Math.max(res, tmp);
}
return res;
}
}
双指针+哈希表
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> dic = new HashMap<>();
int i = -1, res = 0;
for(int j = 0; j < s.length(); j++) {
if(dic.containsKey(s.charAt(j)))
i = Math.max(i, dic.get(s.charAt(j)));
dic.put(s.charAt(j), j);
res = Math.max(res, j - i);
}
return res;
}
}