import java.util.HashMap;
import java.util.Map;
public class Main{
public static void main(String[] args) {
var a = lengthOfLongestSubstring("abacad");
System.out.println(a);
}
static int lengthOfLongestSubstring(String s){
int len = s.length();
//ans记录结果
int ans = 0;
//map记录字母的步长
Map<Character,Integer> map = new HashMap<>();
for (int start = 0,end=0; end<len; end++) {
char alpha = s.charAt(end);
if(map.containsKey(alpha)){
//如果map记录了alpha字符,就更新start
start = Math.max(map.get(alpha),start);
}
//将字符的步长记录
map.put(alpha, end+1);
//更新最长的字符串步长
ans = Math.max(ans,end-start+1);
}
return ans;
}
}
网友评论