leetcode题解3-Longest Substring Without Repeating Characters

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014694994/article/details/79958548

题目:

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.


思路:动态规划寻找最长不重复子串。

代码:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        max_temp,max_res,temp_s = 0, 0, ''
        for c in s:
            if c in temp_s:
                temp_s = temp_s[temp_s.index(c)+1::] + c
                if max_temp >= max_res:
                    max_res = max_temp
                max_temp = len(temp_s)                     
            else:
                temp_s += c
                max_temp += 1
        return max(max_temp, max_res)

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页