首页 > 其他 > 详细

LeetCode-Longest Substring Without Repeating Characters

时间:2015-04-22 07:01:28      阅读:161      评论: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.

 

这道题考察如何维护一个window。因为LC的sample有问题所以正解不确定。

 1 public class Solution {
 2    public static int lengthOfLongestSubstring(String s) {
 3         if(s == null || s.length()==0){
 4             return 0;
 5         }
 6         
 7         int len = s.length();    
 8         int l = 0;
 9         int r = 1;
10         int maxLength = 1;
11        
12         
13         HashSet<Character> set = new HashSet<Character>();
14         set.add(s.charAt(l));
15         
16         while(r < len){
17             if(!set.contains(s.charAt(r))){
18                 set.add(s.charAt(r));
19                 r ++;         
20                 maxLength = Math.max(maxLength, r-l);
21                 
22                 if(r == len){
23                     return maxLength;
24                 }
25                 
26             }
27             else{
28                 while(s.charAt(l) != s.charAt(r)){
29                     set.remove(s.charAt(l));
30                     l ++;
31                 }
32                 l ++;
33                 r ++;   
34                 if(r == len){
35                     return maxLength;
36                 }
37             }
38             
39         }
40         
41         return maxLength;
42     }
43 }

 

LeetCode-Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/incrediblechangshuo/p/4446140.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!