LeetCode – Longest Substring Without Repeating Characters (Java)
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.
Analysis
The basic idea to solve this problem is using an extra data structure to track the unique characters in a sliding window. Both an array and a hash set work for this purpose.
Java Solution 1
The first solution is like the problem of "determine if a string has all unique characters" in CC 150. We can use a flag array to track the existing characters for the longest substring without repeating characters.
public int lengthOfLongestSubstring(String s) { if(s==null) return 0; boolean[] flag = new boolean[256]; int result = 0; int start = 0; char[] arr = s.toCharArray(); for (int i = 0; i < arr.length; i++) { char current = arr[i]; if (flag[current]) { result = Math.max(result, i - start); // the loop update the new start point // and reset flag array // for example, abccab, when it comes to 2nd c, // it update start from 0 to 3, reset flag for a,b for (int k = start; k < i; k++) { if (arr[k] == current) { start = k + 1; break; } flag[arr[k]] = false; } } else { flag[current] = true; } } result = Math.max(arr.length - start, result); return result; } |
Java Solution 2 - HashSet
Using a HashSet can simplify the code a lot.
/* pwwkew i | j | i | j | i | j | */ public int lengthOfLongestSubstring(String s) { if(s==null||s.length()==0){ return 0; } HashSet<Character> set = new HashSet<>(); int result = 1; int i=0; for(int j=0; j<s.length(); j++){ char c = s.charAt(j); if(!set.contains(c)){ set.add(c); result = Math.max(result, set.size()); }else{ while(i<j){ if(s.charAt(i)==c){ i++; break; } set.remove(s.charAt(i)); i++; } } } return result; } |
<pre><code> String foo = "bar"; </code></pre>
-
Technical Interview
-
Alik Elzin
-
Alik Elzin
-
Embe O
-
Jesus Ledesma
-
Jesus Ledesma
-
Jesus Ledesma
-
Bukary Kandeh
-
Ashwini Singh
-
Bukary Kandeh
-
abhishek pandey
-
Sushanta Kumar Sahoo
-
ryanlr
-
Anirudh Jayan
-
Gaurav Gupta
-
Ping Zhang
-
vuqar dadalov
-
Mel
-
Badrinath
-
Milan
-
jeevs
-
Eugene Arnatovich
-
Larry Okeke
-
Larry Okeke
-
Eugene Arnatovich
-
Adrian
-
Truong Khanh Nguyen
-
Ankit Shah
-
CRH
-
pm
-
southie
-
Holden
-
NB****
-
Sahil Singla
-
dtReloaded
-
Satish
-
Vimukthi Weerasiri
-
test
-
Vimukthi Weerasiri
-
Edmond Hong
-
Sahil Singla
-
Adil qureshi
-
Taoufik Bdiri
-
Parag Chaudhari
-
Mehmet
-
ryanlr
-
Tiago
-
ryanlr
-
ryanlr
-
ryanlr
-
ryanlr
-
Arpit Pandey
-
Tarun Singh
-
neckBeardThePirate
-
Zaga
-
Zy
-
Wally Osmond
-
Wally Osmond
-
Jianwei Chen
-
Krzysztof Rajda
-
chitti
-
chitti
-
chitti
-
Alex
-
santhoshvai
-
Jonathan Young
-
santhoshvai
-
Jonathan Young
-
santhoshvai
-
santhoshvai
-
sudhansu jena
-
Cheng Wang
-
Coder
-
amit malik
-
play_boy
-
neal
-
ryanlr
-
ryanlr
-
lee
-
junmin
-
tia