leetcode题解3-Longest Substring Without Repeating Characters

题目:

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)

你可能感兴趣的:(Leetcode题解,动态规划)