标签:
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