• 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 }
  • 相关阅读:
    Spring AOP + Redis 实现针对用户的接口访问频率限制
    Flutter 圆形透明 Loading 弹窗
    VUE 自定义组件的双向数据绑定 和替代钩子
    10个前端技巧
    前端中的数据库
    cors 跨域问题
    promise解决回调地狱问题
    VUE框架JS组件的封装 --Vue.extend
    HBuilderX 用夜神模拟器运行vue项目
    vue关于axios 拦截器的使用
  • 原文地址:https://www.cnblogs.com/Jellylovecode/p/Longest-Substring-Without-Repeating-Characters.html
Copyright © 2020-2023  润新知