zoukankan      html  css  js  c++  java
  • 【LeetCode】Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

    开始的思路是:先将字符存在map中,运用hashmap的key唯一性,和快速查找性,如果遇到重复的,则循环回退到第一次出现的位置的下一个位置继续循环。

    由于map中会用到containsKey的方法增加了时间复杂度,因此超时了

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            Map<Character,Integer> map = new HashMap<Character,Integer>();
            char[] ch = s.toCharArray();
            if(s.equalsIgnoreCase("")||s.isEmpty()||null==s)
                return 0;
            int re=0;
            int max=0;
            for(int i=0;i<ch.length;i++){
                char c = ch[i];
                if(map.containsKey(c)){
                    re=0;
                    i=map.get(c);
                    map = new  HashMap<Character,Integer>();
                    
                }else{
                    map.put(c, i);
                    re++;
                    if(re>max)
                        max=re;
                }
            }
            return max;
            
        }
    }

    经过思考,想到这些字符都是存在于ASCII表中,那申明一个int[128]的数组,来存放,就会保证在O(1)的时间内获取到这个字符是否已经存在,和这个字符的上一个出现位置

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if(s.equalsIgnoreCase("")||s.isEmpty()||null==s)
                return 0;
            int[] init = new int[128];
            Arrays.fill(init, -1);
            char[] ch = s.toCharArray();
            int re = 0;
            int max = 0;
            for(int i=0;i<ch.length;i++){
                char c = ch[i];
                if(init[c]!=-1){
                    re=0;
                    i = init[c];
                    init = new int[128];
                    Arrays.fill(init, -1);
                }else{
                    init[c]=i;
                    re++;
                    if(re>max)
                        max = re;
                }
            }
            return max;
        }
     }
     
  • 相关阅读:
    vue----webpack模板----axios请求
    vue-----meta路由元信息
    vue----webpack模板----全局路由守卫
    vue----webpack模板----局部路由守卫
    vue----webpack模板----组件复用解决方法
    vue----webpack模板----编程式导航
    vue----webpack模板----路由跳转的3中方式
    vue----webpack模板----路由传值
    vue----webpack模板----children子路由,路由嵌套
    vue----webpack模板----路由配置项
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3734144.html
Copyright © 2011-2022 走看看