首页 > 其他 > 详细

Longest Substring Without Repeating Characters 解答

时间:2015-09-16 06:15:54      阅读:158      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!