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;
        }
     }
     
  • 相关阅读:
    PO-审批设置
    DIS-接收方式设置入口
    网约车
    汽车租赁
    共享单车
    共享充电宝
    佛教四大名山|道教四大名山|五岳|名山
    我读过的诗词文章书籍
    我看过的电影
    redis异常解决:jedis.exceptions.JedisDataException: ERR Client sent AUTH, but no password is set
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3734144.html
Copyright © 2011-2022 走看看