IT技术小屋

秋风秋雨,皆入我心

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  38 随笔 :: 1 文章 :: 19 评论 :: 0 Trackbacks
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.

本题比较简单,需要注意的是左指针右移时,需要将它掠过的元素从map中移除。实现代码如下:
 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         int length = s.length();
 4         if (length == 0) return 0;
 5         Map<Character, Integer> map = new HashMap<Character, Integer>();
 6         int ret = 0;
 7         int count = 0;
 8         int start = 0;
 9         for (int i = 0; i < length; i++) {
10             char c = s.charAt(i);
11             if (map.containsKey(c)) {
12                 int newStart = map.remove(c).intValue() + 1;
13                 for (int j = start; j < newStart; j++) {
14                     map.remove(s.charAt(j));
15                 }
16                 start = newStart;
17                 ret = ret < count ? count : ret;
18                 count = i - start + 1;
19             } else {
20                 count++;
21             }
22             map.put(c, i);
23         }
24         return ret < count ? count : ret;
25     }
26 }
posted on 2013-12-22 20:07 Meng Lee 阅读(628) 评论(0)  编辑  收藏 所属分类: Leetcode

只有注册用户登录后才能发表评论。


网站导航: