LeetCode 3. 无重复字符的最长子串(Java版)

原题题解

方法一

穷举所有的子串(定义两个函数):

      ①第一个函数穷举所有可能出现的子串结果,对于字符串的每一个字符,它所构成的子串是下标比它大的所有子串组合

            eg:abc

              对于a,子串有a, ab,abc,

              对于b,子串有b,bc,

              对于c,有子串c

          所以字符串abc的所有的子串为a,ab,abc,b,bc,c

       ②第二个函数用户过滤穷举出来的子串是否重复,用hashset


时间复杂度o(n^3)这种方法会超时

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int res=0;
        for(int i=0;i<s.length();i++){
            for(int j=i+1;j<=s.length();j++){
                if(isTrue(s,i,j))
                    res=Math.max(res,j-i);
            }
        }
        return res;
    }
    public boolean isTrue(String s ,int start,int end){
        Set<Character> set=new HashSet<>();
        for(int i=start;i<end;i++){
            if(set.contains(s.charAt(i)))
            return false;
            set.add(s.charAt(i));    
        }
        return true;
    }
}

方法二

   滑动窗口法:

          定义两个指针,start和end,代表当前窗口的开始和结束位置,同样使用hashset,当窗口中出现重复的字符时,start++,没有重复时,end++,每次更新长度的最大值


时间复杂度o(n)

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int res = 0;
        int end=0,start=0;
        Set<Character> set=new HashSet<>();
        while(start<n && end<n){
           if(set.contains(s.charAt(end))){
               set.remove(s.charAt(start++));
           }else{
               set.add(s.charAt(end++));
               res=Math.max(res,end-start);
           }
            
        }
        return res;
    }

   
}

方法三

      由方法二得到的滑动窗口,每次在[start,end]中如果有重复的,我们的做法是更新窗口从end重新开始,这种方法要求定义一个hashmap保存字符到索引的映射,并且每次都会更新map的值


时间复杂度o(n)

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int res = 0;
        int end=0,start=0;
       Map<Character,Integer> map=new HashMap<>();
        for(;start<n && end<n;end++){
           if(map.containsKey(s.charAt(end))){
               start=Math.max(map.get(s.charAt(end)),start);//从有重复的下一个位置继续找
           }     
            map.put(s.charAt(end),end+1);//map每次更新
            res=Math.max(res,end-start+1);//结果每次更新
        }
        return res;
    }
}
/*
 eg   abca
        start   end   res       map            滑动窗口范围
         0       0     1        a->1                a
         0       1     2        a->1,b->2           a,b
         0       2     3        a->1,b->2,c->3      a,b,c
         1       3     3        a->4,b->2,c->3      b,c,a
*/
                            
                            

  

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值