码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Substring Without Repeating Characters 解答

时间:2015-09-16 06:16:09      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Longest Substring Without Repeating Characters 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4812008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!