zoukankan      html  css  js  c++  java
  • Longest Substring Without Repeating Characters 解答

    Question

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

    Solution

    Use extra map to record whether the character has appeared. Remember to consider the situation of last character. Time complexity O(n), space cost O(n).

     1 public class Solution {
     2     public int lengthOfLongestSubstring(String s) {
     3         if (s == null || s.length() < 1)
     4             return 0;
     5         Map<Character, Integer> map = new HashMap<Character, Integer>();
     6         char[] copy = s.toCharArray();
     7         int length = s.length();
     8         int maxCount = 1;
     9         char start = s.charAt(0);
    10         for (int i = 0; i <= length; i++) {
    11             char tmp;
    12             if (i == length) {
    13                 tmp = s.charAt(length - 1);
    14             } else {
    15                 tmp = s.charAt(i);
    16             }
    17             if (!map.containsKey(tmp)) {
    18                 map.put(tmp, i);
    19             } else {
    20                 int startIndex = map.get(start);
    21                 int dupIndex = map.get(tmp);
    22                 if (startIndex <= dupIndex) {
    23                     if (dupIndex < length - 1)
    24                         start = s.charAt(dupIndex + 1);
    25                     maxCount = Math.max(maxCount, i - startIndex);
    26                 }
    27                 map.put(tmp, i);
    28             }
    29         }
    30         return maxCount;
    31     }
    32 }
  • 相关阅读:
    javaScript学习日记 1 数组
    总结css中单位px和em,rem的区别
    读书摘要
    读书摘要
    各种官方网站汇集
    js相关参考资料
    Node相关参考资料
    Angular【学习笔记】
    Node连接MySQL
    em 和 px相互转换
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4812008.html
Copyright © 2011-2022 走看看