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

Longest Substring Without Repeating Characters

时间:2015-04-10 07:00:16      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

题目: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.

这个题就是快慢指针问题,或者移动窗口? 这类问题每次做还是很小心。主要还是练习少了,并不是很熟练,而且容易搞错。

 1 public int lengthOfLongestSubstring(String s) {
 2         if (s == null || s.length() == 0) {
 3             return 0;
 4         }
 5         int walker = 0;
 6         int runner = 0;
 7         int max = 0;
 8         HashSet<Character> set = new HashSet<Character>();
 9         while (runner < s.length()) {
10             if (!set.contains(s.charAt(runner))) {
11                 set.add(s.charAt(runner));
12             }else {
13                 max = Math.max(max, runner - walker);
14                 while (walker < runner && s.charAt(walker) != s.charAt(runner)) {
15                     set.remove(s.charAt(walker));
16                     walker++;
17                 }
18                 walker++;
19             }
20             runner++;
21         }
22         return Math.max(max, runner - walker);
23     }

 

Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/gonuts/p/4413412.html

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