標籤:
Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
https://leetcode.com/problems/longest-substring-without-repeating-characters/
沒有重複字母的最長公用子串。
雜湊表加雙指標,藉助雜湊表,動態地維護子串。
當一個數不在雜湊表中,只需要移動尾指標,並加入表中。
如果已經存在了,迴圈移動頭指標直到找到這個數,把碰到的元素都從雜湊表中移除。
1 /** 2 * @param {string} s 3 * @return {number} 4 */ 5 var lengthOfLongestSubstring = function(s) { 6 var table = {}, i = 0, j = 0, count = 0, max = 0; 7 while(j < s.length){ 8 if(!table[s[j]]){ 9 table[s[j]] = true;10 j++; count++;11 if(count > max){12 max =count;13 }14 }else{15 while(s[i] !== s[j]){16 table[s[i]] = false;17 i++; count--;18 }19 i++; j++;20 }21 }22 return max;23 };
[LeetCode][JavaScript]Longest Substring Without Repeating Characters