LeetCode 3. Longest Substring Without Repeating Characters

来源:互联网 发布:主成分分析 实际数据 编辑:程序博客网 时间:2024/06/07 12:34

题目:

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.

题意:

给定一个字符串,找出其最长的非重复子串。


题解:(By python)

依次遍历整个子串,用临时子串存储当前非重复子串,

如果当前字符不在子串中,则加入此临时子串,

否则,以当前字符为子串开头,重复上述操作,找到最大子串。


代码如下:

class Solution(object):    def lengthOfLongestSubstring(self, s):        """        :type s: str        :rtype: int        """        cur=''        maxstr=''        count=0        for i in range(len(s)):            if s[i] not in cur: #不在当前子串中                cur+=s[i]                count=count+1                if count>len(maxstr):  #取最大子串                    maxstr=cur                    count=len(cur)            else:                #存在时分割以当前字符为子串起始点                str=cur.split(s[i])                cur=str[1]+s[i]                count=len(cur)        return  len(maxstr)

此时间复杂度为O(n)。


0 0
原创粉丝点击