Longest Substring Without Repeating Characters

这是O(N)的方法,维护窗口的左边和右边,右边不断向左走,当发现这个窗口里面有重复的时候,我们移动左边到重复元素的下一个,跳过中间的字符,因为不会比现在的max更长,而且也始终包含重复的字符。走到无重复了,我们继续移动右边。所以,表面看上去有while loop嵌套在另一个while loop里面,但是我们不重复之前走过的位置,所以时间复杂度还是O(N)的。

public int lengthOfLongestSubstring(String s) {
        if(s==null || s.length() == 0) return 0;
        HashSet<Character> set = new HashSet<Character>();
        int max = 0;
        int walker = 0;
        int runner = 0;
        while(runner < s.length()){
            if(set.contains(s.charAt(runner))){
                max = Math.max(runner-walker,max);
                
                while(s.charAt(walker)!=s.charAt(runner)){
                    set.remove(s.charAt(walker));
                    walker++;
                }
                walker++;
            }
            else set.add(s.charAt(runner));
            runner++;
        }
        max = Math.max(max,runner-walker);
        return max;
    }


下面是动态规划思维用hashset维护一个装满前面遇到的所有char的集合,只要集合增加我们的max就增加,一旦重复,就从头查看。但是因为是O(N*N)的时间复杂度,所以果断TLE过不了的囧。

public int lengthOfLongestSubstring(String s) {
        if(s==null || s.length() == 0) return 0;
        int len = s.length();
        int i = 0;
        int j = 1;
        int max = 0;
        HashSet<Character> set = new HashSet<Character>();
        while(i < len) {
            set.add(s.charAt(i));
            j = i + 1;
            while(j < len) {
                if(!set.contains(s.charAt(j))) {
                    max = Math.max(j - i, max);
                    set.add(s.charAt(j));  
                    j++;
                    //i++;
                }
                else {
                    set.clear(); 
                    break;
                }
            }
            i++;
        }
        return max;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值