算法思想
这道题我已经在 面经上 见到好多次了,所以一定要弄懂;
双指针算法:声明两个指针,i指针循环s字符串,j指针用于去除重复元素,一有重复元素就进行跳转
java 代码
class Solution {
public int longestSubstringWithoutDuplication(String s) {
Map<Character, Integer> map = new HashMap<>(); // 记录 字符索引的位置
int res = 0;
for(int i = 0, j = 0; i < s.length(); i ++)
{
if(map.containsKey(s.charAt(i))) // 说明出现了重复的
j = Math.max(j, map.get(s.charAt(i)) + 1);
map.put(s.charAt(i), i);
res = Math.max(res, i - j + 1);
}
return res;
}
}