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

  • 相关阅读:
    Oracle9使用oradata恢复数据库
    我该怎么安排下属的工作项目经理如何分配任务
    如果说中国的程序员技术偏低,原因可能在这里
    项目经理问:为什么总是只有我在加班 – 挂包袱现象
    【转】面试真经
    [JAVA]PING和TELNET用法介绍
    Hello World 你懂的
    线程间操作控件
    获取客户端相关信息
    winfrom 特效 [转载]
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6508124.html
Copyright © 2011-2022 走看看