首页 > 代码库 > Leetcode-Longest Substring Without Repeating Characters

Leetcode-Longest Substring Without Repeating Characters

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:

 1 public class Solution { 2     public int lengthOfLongestSubstring(String s) { 3         if (s.isEmpty()) return 0; 4         Set<Character> set = new HashSet<Character>(); 5         int head = 0, end = 1; 6         set.add(s.charAt(0)); 7         int maxLen = 1; 8         int curLen = 1; 9         while (end<s.length()){10             char cur = s.charAt(end);11             if (!set.contains(cur)){12                 set.add(cur);13                 curLen++;14                 end++;15             } else {16                 while (s.charAt(head)!=cur){17                     set.remove(s.charAt(head));18                     curLen--;19                     head++;20                 }21                 head++;22                 end++;23             }24             if (curLen>maxLen) maxLen=curLen;25         }26 27 28         return maxLen;29     }30 }

 

Leetcode-Longest Substring Without Repeating Characters