zoukankan      html  css  js  c++  java
  • 剑指Offer48.最长不含重复字符的子字符串

    题目:https://leetcode-cn.com/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof/

    思路:滑动窗口。用map记录每个字符出现的位置。当字符不在map中时,就往map中添加字符和位置,当字符在map中时,考虑map中记录该字符的位置i是不是比窗口的左端小,若是,则不影响当前窗口;否则,要将窗口左端移动至i+1的位置,这样才能保证窗口内部没有重复字符串。

    代码:

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            Map<Character, Integer> map = new HashMap<>();
            int left, right, len;
            left = right = len = 0;
            while(right < s.length()){
                char c = s.charAt(right);
                if(map.containsKey(c) && map.get(c) >= left){
                    left = map.get(c) + 1;
                }
                len = Math.max(len, right - left + 1);
                map.put(c, right);
                right++;
            }
            return len;
        }
    }

     优化:用数字实现哈希表的操作

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int[] map = new int[128];  //长度为128的数组存放字符下表
            for(int i=0; i<128; i++) map[i] = -1;
            int left, right, len;
            left = right = len = 0;
            while(right < s.length()){
                int c = (int)(s.charAt(right));
                if(map[c] >= 0 && map[c] >= left){
                    left = map[c] + 1;
                }
                len = Math.max(len, right - left + 1);
                map[c] = right;
                right++;
            }
            return len;
        }
    }
    执行用时:2 ms, 在所有 Java 提交中击败了100.00%的用户
    内存消耗:38.8 MB, 在所有 Java 提交中击败了58.61%的用户
  • 相关阅读:
    点语法
    第一个OC的类
    gitlab教程
    php接收post的json数组
    phpstorm10.0.2三月22号补丁原来的网址被封了
    冰点下载器在转换pdf的时候出现停止工作
    乱码问题
    有用的网址(php)
    ubuntu16.04安装mysql5.6
    MapUtils常用方法
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14092388.html
Copyright © 2011-2022 走看看