Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
这个题目有三个标签:
[Hash Table] [Two Pointers] [String]
看见这三个标签心中就大概知道应该怎么做了:
class Solution(object):
def lengthOfLongestSubstring(self, s):
n=len(s)
ans=0
for i in xrange(n):
d = {}
j=i
while j<n and s[j] not in d:
d[s[j]]=1
j+=1
ans=max(ans,j-i)
return ans
这里的i和j就相当于两个指针,不是吗?
但是,这样做明显复杂了,第9行的赋值是无用的,我只是想用key,value是无用的,那我是不是可以把value赋值为 自字符串的下标呢?
参考discuss的答案,更改如下:
class Solution(object):
def lengthOfLongestSubstring(self, s):
d = {}
ans=begin=0
for i in xrange(len(s)):
if s[i] in d and begin<=d[s[i]]:
begin=d[s[i]]+1
else:
ans=max(ans,i-begin+1)
d[s[i]]=i
return ans
本文探讨了如何寻找给定字符串中最长的无重复字符子串,并提供了两种使用哈希表和双指针技术实现的方法。通过具体示例,如abcabcbb和pwwkew等,展示了不同算法的运作过程。
706

被折叠的 条评论
为什么被折叠?



