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出现,一个不允许。

  • 相关阅读:
    vue登录注册及token验证
    react实现登录注册
    React Native仿京东客户端实现(首页 分类 发现 购物车 我的)五个Tab导航页面
    进度条效果
    手风琴切换效果
    React实现了一个鼠标移入的菜单栏效果
    react购物车
    react实现tab切换效果
    网络缓存
    java线程面试手写题
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6508124.html
Copyright © 2011-2022 走看看