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;
        }
     }
     
  • 相关阅读:
    安卓 日常问题 工作日志20
    安卓 日常问题 工作日志19
    安卓 日常问题 工作日志18
    安卓 日常问题 工作日志17
    安卓 日常问题 工作日志16
    对json进行排序处理
    Eclipse错误: 找不到或无法加载主类或项目无法编译10种解决大法!----------------------转载
    hibernate hql语句 投影查询的三种方式
    新的开始2018/6/8
    SSM搭建
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3734144.html
Copyright © 2011-2022 走看看