zoukankan      html  css  js  c++  java
  • 3. Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters.

    Examples:

    Given "abcabcbb", the answer is "abc", which the length is 3.

    Given "bbbbb", the answer is "b", with the length of 1.

    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    本题和longest substring with at most two distinct characters有点像,只不过本题是不能出现重复的character,那道题说的是不能超过两个,看了答案的做法,想法是,遍历字符串,用一个hashmap来存储字符和其索引,如果出现了重复的字符,则将双指针里面的低指针指向出现该重复字符的最后一个索引+1,如果没有出现重复字符,则将当前字符加入hashmap里面,并且计算一次最大长度,代码如下:

     1 public class Solution {
     2     public int lengthOfLongestSubstring(String s) {
     3         int len = 0;
     4         int hi = 0;
     5         int lo = 0;
     6         Map<Character,Integer> map = new HashMap<Character,Integer>();
     7         for(;hi<s.length();hi++){
     8             if(map.containsKey(s.charAt(hi))){
     9                 lo = Math.max(lo,map.get(s.charAt(hi))+1);
    10             }
    11             map.put(s.charAt(hi),hi);
    12             len = Math.max(len,hi-lo+1);
    13         }
    14         return len;
    15     }
    16 }

    本题不可以用Longest Substring with At Most Two Distinct Characters的方法做,是因为,那道题是每次删除索引map里面最前面的字符的最前索引值的字符,而这道题是删除重复出现的字符的索引值,也就是说,一个允许重复char出现,一个不允许。

  • 相关阅读:
    js变量类型
    js词法分析
    ORACLE 查找字段在哪些表里存在
    主外键约束的关闭和启用
    pl/sql developer 编码格式设置(转)
    WIN7 Net Configuration Assistant打不开
    Kettle 连接失败 Oracle 数据库报 ora-12505 的解决方法(转)
    正则表达式30分钟入门教程(转)
    设置程序的多个入口,进行动态的显示
    应用多入口配置
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6508124.html
Copyright © 2011-2022 走看看