题解 | #最长不含重复字符的子字符串#
最长不含重复字符的子字符串
http://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
export function lengthOfLongestSubstring(s: string): number {
// write code here
const wordMap = new Map();
let maxLen = 1,lastVal = 1;
wordMap.set(s[0], 0);
for(let i=1;i<s.length;i++) {
const lastSimilarIdx = wordMap.get(s[i]);
if(lastSimilarIdx === undefined) {
lastVal += 1;
} else {
const dis = i - lastSimilarIdx;
if(dis > lastVal) {
lastVal += 1;
} else {
lastVal = dis;
}
}
maxLen = Math.max(maxLen, lastVal);
wordMap.set(s[i], i);
}
return maxLen;
}