3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
Similar: 159. Longest Substring with At Most Two Distinct Characters
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 HashMap<Character, Integer> map = new HashMap<Character, Integer>(); 4 int max = 0; 5 int start=0; 6 for (int i = 0; i < s.length(); i++) { 7 max = max > (i - start) ? max : (i-start); // [start,i), i is not included 8 char c = s.charAt(i); 9 if (map.containsKey(c)) { 10 int j = map.get(c); 11 while (start <= j) { 12 map.remove(s.charAt(start)); 13 start++; 14 } 15 } 16 map.put(c, i); 17 } 18 max = max > (s.length() - start) ? max : (s.length()-start); // As length = [start,i), i is not included 19 return max; 20 } 21 }