zoukankan      html  css  js  c++  java
  • 3. Longest Substring Without Repeating Characters

    O(n^2)

    from collections import defaultdict
    
    
    def solve(s):
        if not isinstance(s, str) or len(s) == 0:
            return 0
        idx_set = defaultdict(set)
        s_len = len(s)
        res = ''
        for i in range(s_len):
            for i_index in range(s_len-i):
                if s[i_index + i] not in idx_set[i]:
                    idx_set[i].add(s[i_index + i])
                else:
                    if len(res) < len(idx_set[i]):
                        res = ''.join(idx_set[i])
                    break
        return res
    
    
    print solve('pwwkew')

    solution 2: maintain a window:

    def solve1(s):
        if not isinstance(s, str) or len(s) == 0:
            return ''
        the_list = list()
        res = ''
        for c in s:
            if c not in the_list:
                the_list.append(c)
            else:
                if len(res) < len(the_list):
                    res = ''.join(the_list)
                the_list_copy = copy.deepcopy(the_list)
                for ts in the_list_copy:
                    if ts == c:
                        the_list.remove(ts)
                        break
                    else:
                        the_list.remove(ts)
                the_list.append(c)
        if len(res) < len(the_list):
            res = ''.join(the_list)
        return res
    
    
    print solve1("pwwkew")
  • 相关阅读:
    2014第16周六
    2014第16周五
    2014第16周四
    2014第16周三CSS布局再学习摘录
    2014第16周二
    2014第16周一
    2014第15周日
    2014第15周六
    2014第15周五
    SDN:软件定义网络
  • 原文地址:https://www.cnblogs.com/geeklove01/p/9483649.html
Copyright © 2011-2022 走看看