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.

本题是想获得s中不重复的子串,最简单的方法就是使用set保存已经遍历过的字符,一旦出现重复便记录该字符串长度即可,这种方法因为重复率较高,所以效率很低,只击败了4%的用户。代码入下:

    public static int lengthOfLongestSubstring(String s) {
        if(s.length() < 2)
            return s.length();
        int res = 0;
        for(int i=0; i<s.length()-1; i++){
            Set<Character> map = new HashSet<>();
            map.add(s.charAt(i));
            int j = i+1;
            for(; j<s.length(); j++)
                if(!map.add(s.charAt(j)))
                    break;
            res = Math.max(res, j-i);
        }
        return res;
    }

方法二,使用map来保存每个字符的索引位置信息,然后引入j游标记录字符串左边的起始位置,遍历索引i相当于其右边结束位置。这里需要注意的是,j更新的时候要更新为j和map.get(s.charAt(i))+1二者中较大的一个。比如“abba”,当遍历到第二个a时,j应该保持为原始的2,而不应该为第一个a的下一个(即1)。代码入下,这种方法可以击败64%的用户:

    public int lengthOfLongestSubstring1(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max=0;
        for (int i=0, j=0; i<s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
            //注意这里一定要将j赋值为二者的最大值,以防出现上面所说的情况
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
        }
        return max;
    }

方法三,使用数组来代替map,这是一种常用的方法。将map的key作为数组的索引,value作为数组的值进行转化。代码入下,可以击败97%的用户:

    public int lengthOfLongestSubstring2(String s) {
        int[] mOccur = new int[256];
        int maxL = 0;
        for(int i = 0, j = 0; i < s.length(); ++i){
            char ch = s.charAt(i);
            ++mOccur[ch];
            //注意这个循环的作用,对于“abba”,先将a取出,再将一个b取出。对于“abcab”直接将a取出即可。非常机智的做法
            while(mOccur[ch] > 1){
                --mOccur[s.charAt(j++)];
            }
            maxL = Math.max(maxL, i - j + 1);
        }
        return maxL;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值