leetcode 3 Longest Substring Without Repeating Characters,leetcoderepeating
分享于 点击 3977 次 点评:1
leetcode 3 Longest Substring Without Repeating Characters,leetcoderepeating
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.
用s表示该字符串。直接来硬的,简单粗暴,超时。。
那就用DP吧
a[*][i]表示s中前i个里出现*的次数,b[i]表示从s[i]往前(包括s[i])的最长无重复字母子串。那么
b[i]=b[i-1]+1, if (之前没出现过s[i]) a[s[i],i-1]==0 or (之前的b[i-1]里没有出现过s[i]) a[s[i],i-1]==a[s[i],i-1-b[i-1]];
否则,b[i]=b[i]=i-j 其中j是上一次出现s[i]的位置。
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
if s=='':
return 0
maxlen=len(set(s))
ans=1
l=len(s)
a={}
a[s[0]]={}
a[s[0]][0]=1
b={}
b[0]=1
for i in xrange(1,l):
if s[i] not in a:
a[s[i]]={}
a[s[i]][i]=1
else:
for j in xrange(i,-1,-1):
if j in a[s[i]]:
break
for k in xrange(j,i):
a[s[i]][k]=a[s[i]][j]
a[s[i]][i]=a[s[i]].get(j,0)+1
if a[s[i]].get(i-1,None)==None or a[s[i]].get(i-1,None)==a[s[i]].get(i-1-b[i-1],None):
b[i]=b[i-1]+1
else:
for j in xrange(i-1,-1,-1):
if s[i]==s[j]:
b[i]=i-j
break
if ans<b[i]:
ans=b[i]
if b[i]==maxlen:
return maxlen
return ans
虽然过了,但是按时间排名有点靠后呢,,再改进一下吧:不要数组a了,使用字典记录每个字母上一次出现的位置
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
if s=='':
return 0
maxlen=len(set(s))
ans=1
l=len(s)
b={}
b[0]=1
last={}
last[s[0]]=0
for i in xrange(1,l):
# pdb.set_trace()
if (s[i] not in last) or (i-last[s[i]]>b[i-1]):
b[i]=b[i-1]+1
elif s[i] in last:
b[i]=i-last[s[i]]
else:
b[i]=b[i-1]
if ans<b[i]:
ans=b[i]
if b[i]==maxlen:
return maxlen
last[s[i]]=i
return ans
从338 ms 降低到97
ms相关文章
- 暂无相关文章
用户点评