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 }
  • 相关阅读:
    iPhone X 的“刘海”正是苹果的品牌象征
    中国首届原型设计大赛在成都举办
    hdu1114Piggy-Bank(完全背包)
    hdu2602Bone Collector(01背包)
    漏洞百出的线段树!!
    hdu1078FatMouse and Cheese
    hdu2859Phalanx
    poj3186Treats for the Cows(区间dp)
    uva10088格点多边形
    快速幂快速乘
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4812008.html
Copyright © 2011-2022 走看看