美文网首页
3. Longest Substring Without Rep

3. Longest Substring Without Rep

作者: 撸完代码送快递 | 来源:发表于2019-07-20 20:35 被阅读0次

以下是第一次提交的代码,存在超时问题

    public int lengthOfLongestSubstring(String s) {
        List<Character> characterList = new ArrayList<>();
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
            if (characterList.contains(s.charAt(i))) {
                res = Math.max(res, characterList.size());
                int index = characterList.indexOf(s.charAt(i));
                //截取重复位置之后的List
                characterList = characterList.subList(index + 1, characterList.size());
                characterList.add(s.charAt(i));
            } else {
                characterList.add(s.charAt(i));
                res = Math.max(res, characterList.size());
            }
        }
        return res;
    }

下边是看的官方答案,滑动窗口的一个版本。

    public int lengthOfLongestSubstring1(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();
        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++));
                ans = Math.max(ans, j - i);
            }
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }

感觉和我的并没什么差别,而且它还多便利了很多次。这是为什么??


优化的滑动窗口解法

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);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-by-leetcod/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

相关文章

网友评论

      本文标题:3. Longest Substring Without Rep

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