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

  • 相关阅读:
    10. 正则表达式匹配
    5. 最长回文子串
    板子总结
    2020: 学生查询
    解决apt-get出错
    03如何计算算法的复杂度
    ad如何从PCB中导出元件封装库
    调车遇到的问题及解决办法
    java报错与解决方法总结
    SWD下载k60
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6508124.html
Copyright © 2020-2023  润新知