码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode -- Algorithms -- 3_ Longest Substring Without Repeating Characters

时间:2017-09-09 17:19:30      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:perm   erro   sts   sel   blog   import   from   end   rto   

from itertools import permutations

class Solution(object):
 
    def lengthOfLongestSubstring(self, s):
        temp = 0
        new_list = []
        new_string = []
        all_sub = []
        l = ‘‘

        # get the new string without duplicate 
        for i in range(len(s)):
            if s[i] not in new_list:
                new_list.append(s[i])

        if len(new_list) == 1:
            temp = 1

        else:
            for j in range (len(new_list),1,-1):
                all_sub += list(permutations(new_list,j))  #get all the combinations with list
                for k in range(len(all_sub)):
                    for e in range(len(all_sub[k])):
                        l += all_sub[k][e]
                    new_string.append(l)
                    l = ‘‘

                    for f in range(len(new_string)):
                        try:
                            if new_string[f] in s:
                                temp = len(new_string[f])
                                raise ValueError
                        except ValueError:
                                return temp 

                all_sub = []
 
 
        return temp
        
        

 

 

But failed with time exceed. The one with better solution is shown as below:

class Solution:
    # @param {string} s
    # @return {integer}
    def lengthOfLongestSubstring(self, s):
        start_pos = 0
        current_pos = -1    # consider blank string case
        max_length = 0
        char_pos = {}
        for current_pos in range(len(s)):
            if s[current_pos] in char_pos and char_pos[s[current_pos]] >= start_pos :
                max_length = max(max_length, current_pos - start_pos)
                start_pos = char_pos[s[current_pos]] + 1
            char_pos[s[current_pos]] = current_pos
        return max(max_length, current_pos - start_pos + 1)

 

 

Much simpler.

Ich denke, dass muss ich h?rter arbeiten.  N?chste Station, Algorithms und Daten Strukturen !!

leetcode -- Algorithms -- 3_ Longest Substring Without Repeating Characters

标签:perm   erro   sts   sel   blog   import   from   end   rto   

原文地址:http://www.cnblogs.com/Shareishappy/p/7498601.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!