美文网首页
LeetCode热题3:Longest Substring Wi

LeetCode热题3:Longest Substring Wi

作者: 雪飘千里 | 来源:发表于2020-01-10 16:40 被阅读0次

题目:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

思路:找这种没有重复字符的连续字符串,使用滑动窗口是最方便的,使用spark streaming或者flink处理过流式数据的应该对滑动窗口函数很熟悉。至于说是没有重复字符、最长,这些只是滑动窗口函数中要实现的过滤条件而已。

滑动窗口:使用两个变量i,j来标识滑动窗口起始结束标识
重复字符:使用hash表判断;

代码实现一:
public class lengthOfLongestSubstring {

    public static void main(String[] args) {
        String str = "aabaab!bb";
        System.out.println(slution1(str));
    }

    public static int slution1(String str){
        int maxLength=0;
        Set<Character> set = new HashSet<>();
            //通过不断的递增i,j来构成滑动窗口
        for(int i=0,j=0;j<str.length();j++) {
            //set不包含的时候,把字符添加到set中,同时计算滑动窗口最大长度
            if (!set.contains(str.charAt(j))) {
                set.add(str.charAt(j));
                //滑动窗口最大长度 取 滑动长度当前长度 (j - i+1) 和 历史最大长度(maxLength)的  最大值
                maxLength = Math.max(maxLength, j - i+1);
            } else {
                //当set包含的时候,滑动窗口起始值i前进一位,结束值j保持不变
                set.remove(str.charAt(i));
                i++;
                j--;
            }
        }
        return maxLength;
    }
}
image.png

时间复杂度:O(2n),i和j都需要循环一遍

代码实现二:

上面的方法其实还可以再优化一下,当set包含的时候,其实没必要让i++,可以直接让i跳转到重复字符的下一位,这样可以减少循环次数。

public class lengthOfLongestSubstring {

    public static void main(String[] args) {
        String str = "aabaab!bb";
        System.out.println(solution2(str));
    }

    public static int solution2(String str){
        int maxLength=0;
        //使用hashMap来存储字符和其所在的位置
        Map<Character,Integer> map = new HashMap<>();
        for(int i=0,j=0;j<str.length();j++) {
            //map包含的时候,
            if(map.containsKey(str.charAt(j))){
                //i = Math.max(map.get(str.charAt(j))+1,i);
                //i只能前进,不能后退,所有跳转之前要先判断
                if(map.get(str.charAt(j))+1>i){
                    //i直接跳转到字符上次出现位置的下一位
                    i = map.get(str.charAt(j))+1;
                }
            }
            //map中存储的是字符的最新位置
            map.put(str.charAt(j),j);
            //滑动窗口最大长度 取 滑动长度当前长度 (j - i+1) 和 历史最大长度(maxLength)的  最大值
            maxLength = Math.max(maxLength,j-i+1);
        }
        return maxLength;
    }
}

image.png

相关文章

网友评论

      本文标题:LeetCode热题3:Longest Substring Wi

      本文链接:https://www.haomeiwen.com/subject/juzjactx.html