zoukankan      html  css  js  c++  java
  • [leetcode]Longest Substring Without Repeating Characters

    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.

    算法分析:

    思路1:

    最土的方法求出所有的子串,继而求出最长的不重复子串。不用试,肯定超时

    思路2:

    维护一个map,key存储字符,value存储其在s中的下标。当遇到之前出现的字符(下表为j)时,将子串起始下标begin更新为j+1。同时维护maxLength;

    代码如下:

     1 public int lengthOfLongestSubstring(String s) {
     2         int length = s.length();
     3         Map<Character,Integer> hash = new HashMap<Character,Integer>();
     4         int currentLength  = 0;
     5         int maxLength = 0;
     6         int from = 0;
     7         for(int i = 0; i < length; i++){
     8             if(!hash.containsKey(s.charAt(i))){
     9                 currentLength++;
    10                 hash.put(s.charAt(i), i);
    11             }else{
    12                 if(from <= hash.get(s.charAt(i))){
    13                     from = hash.get(s.charAt(i)) + 1;
    14                     currentLength = i - hash.get(s.charAt(i));
    15                     }else{
    16                     currentLength++;
    17                 }
    18                                 hash.put(s.charAt(i), i);
    19             }
    20             if(currentLength > maxLength){
    21                 maxLength = currentLength;
    22             }
    23         }
    24         return maxLength;
    25     }
    View Code

    思路2优化:

     1 public class Solution {
     2     public int lengthOfLongestSubstring(String s) {
     3         if (s == null || s.length() == 0)
     4             return 0;
     5         int[] hash = new int[256];
     6         Arrays.fill(hash, -1);
     7         int maxLength = 0;
     8         int pre = -1;
     9         for (int i = 0; i < s.length(); i++) {
    10             if (hash[s.charAt(i)] > pre) {
    11                 pre = hash[s.charAt(i)];
    12             }
    13             maxLength = Math.max(maxLength, i - pre);
    14             hash[s.charAt(i)] = i;
    15         }
    16         return maxLength;
    17     }
    18 }
  • 相关阅读:
    删除字符串组中相同元素,并删除值为空的元素 (转载,笔记)
    获取操作系统语言
    .net 传递中文参数解决办法
    古怪问题:vs2003程序 在繁体平台下控件位置发生变化
    Godaddy邮箱C#发送邮件设置
    无法显示隐藏文件的解决方法
    虚拟机文件
    sql 2000 修复问题
    看QQ是否在线
    sql 知识摘录
  • 原文地址:https://www.cnblogs.com/huntfor/p/3883749.html
Copyright © 2011-2022 走看看