• LeetCode: Longest Substring Without Repeating Characters


     1 /**
     2  * 
     3  */
     4 package solution;
     5 
     6 import java.util.HashMap;
     7 
     8 /**
     9  * @author whh
    10  * 
    11  *         Given a string, find the length of the longest substring without
    12  *         repeating characters. For example, the longest substring without
    13  *         repeating letters for "abcabcbb" is "abc", which the length is 3. For
    14  *         "bbbbb" the longest substring is "b", with the length of 1.
    15  */
    16 public class LongestSubstringWithoutRepeatingCharacters {
    17 
    18     /**
    19      * @param args
    20      */
    21     public static void main(String[] args) {
    22         String s1 = "abcabcbb", s2 = "aaa", s3 = "abcdefghijklmnopqrstuvwxyz";
    23         String s4 = "wlrbbmqbhcdarzowkk";
    24         String s5 = "qopubjguxhxdipfzwswybgfylqvjzhar";
    25         System.out.println(lengthOfLongestSubstring(s1));
    26         System.out.println(lengthOfLongestSubstring(s2));
    27         System.out.println(lengthOfLongestSubstring(s3));
    28         System.out.println(lengthOfLongestSubstring(s4));
    29         System.out.println(lengthOfLongestSubstring(s5));
    30 
    31     }
    32 
    33     /**
    34      * @param s
    35      * @return
    36      */
    37     public static int lengthOfLongestSubstring(String s) {
    38 
    39         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    40 
    41         int begin = 0, maxLength = 0;
    42         for (int end = 0; end < s.length(); end++) {
    43             Character character = s.charAt(end);
    44             if (!map.containsKey(character)) {
    45                 map.put(character, 1);
    46             } else {
    47                 map.put(character, map.get(character) + 1);
    48             }
    49 
    50             if (map.get(character) == 2) {
    51                 while (map.get(s.charAt(begin)) <= 1) {
    52                     map.put(s.charAt(begin), map.get(s.charAt(begin)) - 1);
    53                     begin++;
    54                 }
    55                 map.put(s.charAt(begin), map.get(s.charAt(begin)) - 1);
    56                 begin++;
    57             }
    58             if ((end - begin + 1) >= maxLength) {
    59                 maxLength = end - begin + 1;
    60             }
    61         }
    62 
    63         return maxLength;
    64     }
    65 }
  • 相关阅读:
    linux中bin和sbin目录的主要区别
    C# 值类型 引用类型 作为参数传递区别
    绿色免安装电视直播软件viviplayer
    [转]中科大校长建议停止以行政主导的高校评估
    MDS 7.0 使用中的问题 2(数据交换中图元的丢失)
    怪异的慢递公司一统快递
    [转]全国最好的医院列表
    多普达D600 问题集锦
    推荐PDG阅读器UnicornViewer
    [转]《乒乓世界》封面故事:中国男乒直板三人行
  • 原文地址:https://www.cnblogs.com/Jellylovecode/p/Longest-Substring-Without-Repeating-Characters.html
Copyright © 2020-2023  润新知