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.

    题目含义:获取最长子串,要去子串中没有重复字符

     1     public int lengthOfLongestSubstring(String s) {
     2         if (s.length() == 0) return 0;
     3         HashMap<Character,Integer> map = new HashMap<>(); //记录每个字符最后一次出现的位置
     4         int max=0;
     5         int j=0;
     6         for (int i=0;i<s.length();i++)
     7         {
     8             char letter = s.charAt(i);
     9             if (map.containsKey(letter))
    10             {
    11                 j = Math.max(j,map.get(letter)+1); //j表示上一个letter后面的字符位置
    12             }
    13             map.put(letter,i);//记录每个字符最后一次出现的位置
    14             max = Math.max(max,i-j+1);//上一个letter后面的字符到i的长度,也就是非重复子串的长度
    15         }
    16         return max;        
    17     }
  • 相关阅读:
    android 入门-Activity及 字体
    android 入门-安装环境
    PS 零基础训练1
    txt操作
    C#重绘TabControl
    ini操作
    C#编写ActiveX控件
    远程目录和文件判断
    c#一些操作
    c#消息窗体
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7682418.html
Copyright © 2011-2022 走看看