1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
class : def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if not s: return 0 memo = set() self.max_length = float('-inf') for i in range(len(s)): if self.max_length >= len(s) - i: break self.helper("", i, s, memo) return self.max_length def helper(self, path, ind, string, memo): self.max_length = max(self.max_length, len(path)) if ind >= len(string): return
if string[ind] not in path: path+=string[ind] self.helper(path, ind+1, string, memo) return class Solution2: def lengthOfLongestSubstring(self, s): if not s: return 0 i = j = 0 res = 0 memo = set() while i < len(s) and j < len(s): if s[j] not in memo: memo.add(s[j]) res = max(res, j - i + 1) j+=1 else: memo.remove(s[i]) i += 1 return res class Solution: def lengthOfLongestSubstring(self, s): if not s: return 0 res = 0 i = j = 0 dic = {} while j < len(s): if s[j] in dic: i = max(dic[s[j]], i) res = max(res, j - i + 1) dic[s[j]] = j + 1 j+=1 return res
|
近期评论