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

  • 相关阅读:
    【题解】2020 年电子科技大学 ACMICPC 暑假前集训 数据结构
    【逆向】某触控板驱动分析过程
    SME 2019 ACM 题解
    数据结构 & 算法模板汇总
    VS2010win32下cocos2dx控制台打印的方法
    CDMA写码与鉴权(转载)
    mapxtreme开发小结2(c#)
    LONG GetWindowLong函数功能
    无边框的对话框的大小拖动实现
    YUV介绍
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6508124.html
Copyright © 2011-2022 走看看