您的位置:首页 > 其它

LeetCode003__Longest Substring Without Repeating Characters

2016-09-05 18:24 495 查看
第一行留给国际惯例,放题目:

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.

为什么第一想法就是HashMap啊,O(n)的时间代价,恩,就这么干!

思路是这样的:

1、建立一个字母表,将字符串转换存入表中(建立HashMap)

2、删选重复的字母,找到最大子序列

第一次(¥很奇怪为啥要这样说,搞得像一次通不过一样¥):

class Solution(object):
def lengthOfLongestSubstring(self, s):

flag=[]
temp=[]
sub=[]
for i in range(127):
flag.append(0)

for x in range(len(s)):
num=ord(s[x])%127
if flag[num]==0:
flag[num]=1
temp.append(s[x])
elif len(sub)>=len(temp):
temp=[]
else:
sub=temp[:]
temp=[]

return len(sub)


果然没通过



很奇怪,到底哪里错了呢?

原来犯了严重的逻辑错误,当最大序列持续到末尾时候,序列在temp中而没有传递到sub中。小改一下

class Solution(object):
def lengthOfLongestSubstring(self, s):

flag=[]
temp=[]
sub=[]
for i in range(127):
flag.append(0)

for x in range(len(s)):
num=ord(s[x])%127
print(num)
if flag[num]==0 and len(sub)<=len(temp):
flag[num]=1
temp.append(s[x])
sub=temp[:]
print(temp)

else:
temp=[]

return len(sub)


第二次:



太打击人了

至少要两层循环,再来

class Solution(object):

def lengthOfLongestSubstring(self, s):

flag=[]
for x in range(127):
flag.append(-1)
temp=[]

sub=[]

i=0
while i<len(s):
num=ord(s[i])%127
print(s[i])

if flag[num]==-1 and len(sub)<=len(temp):
flag[num]=i
temp.append(s[i])
sub=temp[:]
i=i+1
print(temp)

elif flag[num]==-1 and len(sub)>len(temp):
flag[num]=i
temp.append(s[i])
i=i+1

else:
i=flag[num]+1
temp=[]
for x in range(127):
flag[x]=-1
print(flag[num+1])

return len(sub)


不说话了,直接上结果:



得找找其他方法了

试了试将复制步骤删除,直接统计数字:

class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
dict={}
t=0
i=0
sub=0
while i<len(s):
if s[i] in dict:
i=dict[s[i]]+1
dict={}
t=0

elif sub<t+1:
dict[s[i]]=i
t=t+1
i=i+1
sub=t
else:
dict[s[i]]=i
t=t+1
i=i+1
return sub


这次通过了。



感觉应该不是这个问题,还是存在其他问题。(未完)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: