请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
"abcabcbb"
3
因为无重复字符的最长子串是"abc",所以其长度为 3
"pwwkew"
3
因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是子串的长度,"pwke" 是一个子序列,不是子串。
"ipalfish"
7
因为无重复字符的最长子串是"palfish",所以其长度为 7。
function lengthOfLongestSubstring( s ) { // write code here //1. 用一个map存储子字符串信息,key-字符,value-下标。 //2. 滑动窗口,双指针,begin,end。再用一个变量maxLength记录最大长度。 //3. end变量字符串,如果map中有重复字符,maxLength = max(maxLength, // end-begin),更新begin = max(begin, value+1)。 //4. 更新map信息。 //5. 最后再更新一次maxLength。 const map = new Map(); let begin = 0; let end = 0; let maxLength = 0; while (end < s.length) { const char = s.charAt(end); if (map.has(char)) { maxLength = Math.max(maxLength, end - begin); begin = Math.max(begin, map.get(char) + 1); } map.set(char, end); end++; } maxLength = Math.max(maxLength, end - begin); return maxLength; }
# # # @param s string字符串 # @return int整型 # from collections import defaultdict class Solution: def lengthOfLongestSubstring(self , s ): # write code herekm window = dict.fromkeys(s, 0) left = 0 right = 0 res = 0 while right < len(s): c = s[right] right += 1 window[c] += 1 while window[c]>1: d = s[left] left += 1 window[d] -= 1 res = max(res, right-left) return res