leetcode3. Longest Substring Without Repeating Characters

来源:互联网 发布:星际淘宝网下载 编辑:程序博客网 时间:2024/05/01 11:22

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.

思路一:

981 / 981 test cases passed.
Status: Accepted
Runtime: 604 ms
借用队列的方法,想象下推箱子

import Queueclass Solution(object):    def lengthOfLongestSubstring(self, s):        q=Queue.Queue(maxsize=0)        count=[]        list_=[]        if len(s)==0:            return 0        for i in range(len(s)):            if s[i] not in list_:                q.put(s[i])                list_.append(s[i])            else:                count.append(q.qsize())                flag=1                while flag:                    value=q.get()                    if value==s[i]:                        flag=0                    else:                        list_.remove(value)                q.put(s[i])        count.append(q.qsize())        return max(count)

思路二:
标记位置,遍历字符串s,index=max(index,doc[s[i]]+1),doc[s[i]]=i,
981 / 981 test cases passed.
Status: Accepted
Runtime: 112 ms
Submitted: 0 minutes ago

class Solution(object):    def lengthOfLongestSubstring(self, s):        if len(s)==0:            return 0        max_=0        dic={}        index=0        if len(s)==0:            return 0        for i in range(len(s)):            if s[i] not in dic:                dic.setdefault(s[i],i)            else:                max_=max(max_,i-index)                index=max(index,dic[s[i]]+1)                dic[s[i]]=i        max_=max(max_,len(s)-index)        return max_
0 0
原创粉丝点击