zoukankan      html  css  js  c++  java
  • [LeetCode]3.无重复字符的最长子串

    自己的解法

    将字符串转化为字符数组,从首字符向后扫描字串,找到不重复的最长字串

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            char[] chars = s.toCharArray();
            HashSet<Character> hs = new HashSet();
            int size = 0;
            for(int j = 0; j < chars.length; j++){
                for(int i = j; i < chars.length; i++){
                    if(hs.contains(chars[i])){
                            break;
                    }
                    hs.add(chars[i]);
                }
                if(size < hs.size()){
                    size = hs.size();
                }
                hs.clear();
            }
            return size;
        }
    }
    

    滑动窗口

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            HashSet<Character> hs = new HashSet<>();
            int i = 0, j= 0;
            int n = s.length();
            int ans = 0;
            while( i < n && j < n){
                if(!hs.contains(s.charAt(j))){
                    hs.add(s.charAt(j++));
                    ans = Math.max(ans, j - i);
                }
                else{
                    hs.remove(s.charAt(i++));
                }
            }
            return ans;
        }
    }
    

    优化滑动窗口

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int n = s.length();
            int ans = 0;
            Map<Character,Integer> map = new HashMap<>();
            for(int i = 0, j = 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;
        }
    }
    

    假设字符集为 ASCII 128

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int[] index = new int[128];
            int n = s.length();
            int ans = 0;
            for(int i=0, j = 0; j < n; j++){
                i = Math.max(index[s.charAt(j)],i);
                ans = Math.max(ans,j-i+1);
                index[s.charAt(j)] = j+1;
            }
            return ans;
        }
    }
    
  • 相关阅读:
    sequelize 批量添加和更新数据 bulkCreate
    js 线程和进程的关系
    mysql 索引 笔记1
    mysql 主键
    loj2292 「THUSC 2016」成绩单
    loj2291 「THUSC 2016」补退选
    cf984c Finite or not?
    cf984e Elevator
    loj2540 「PKUWC 2018」随机算法
    luoguT30204 偷上网
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13860111.html
Copyright © 2011-2022 走看看