3.无重复字符的最长字串--HashSet<> VS HashMap<>

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

  我首先想到了滑动窗口,但还是老问题,不知道该如何实现,只能一边又一边的看代码,熟悉Java的基本类型和方法。

一、HashSet法

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>(); //HashSet 是一个由 HashMap 实现的集合。元素无序且不能重复
        int ans = 0, i = 0, j = 0;
        while (i < n && j < n) {
            // try to extend the range [i, j]
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));     //这里是先传值j,再j+1
                ans = Math.max(ans, j - i);
            }
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }
}

关于HashSet参考:https://www.cnblogs.com/ysocean/p/9809046.html#_label0

二、HashMap法

  法一在执行过程中发现这样一个问题:例如字符串"abcdefjhijk...",如果i在a的位置,j扫描到了k前,发现重复,便停下来从i+1开始新的窗口扫描,而这无疑时没有意义的,一直到i加到第一个重复字符之后。

  于是想到,应当把i的值立即转为j+1即可避免这样的浪费,这就要求我们根据重复值寻找它的记录容器中的索引,因此用到了HashMap。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i); //get()根据键返回值,即数组下标+1(从1开始)
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}

关于HashMap参考:https://www.cnblogs.com/ysocean/p/8711071.html#_label2

原文地址:https://www.cnblogs.com/learn-with-blog/p/12457075.html