Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: 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.
Use HashSet
1 class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if (s == null || s.length() < 0) return 0; 4 int res = 0; 5 int l = 0, r = 0; 6 HashSet<Character> set = new HashSet<>(); 7 for (; r < s.length(); r ++) { 8 if (set.contains(s.charAt(r))) { 9 while (l <= r && set.contains(s.charAt(r))) { 10 set.remove(s.charAt(l)); 11 l ++; 12 } 13 } 14 set.add(s.charAt(r)); 15 res = Math.max(res, r - l + 1); 16 } 17 return res; 18 } 19 }
Use HashMap
1 public int lengthOfLongestSubstring(String s) { 2 if (s.length()==0) return 0; 3 HashMap<Character, Integer> map = new HashMap<Character, Integer>(); 4 int max=0; 5 for (int i=0, j=0; i<s.length(); ++i){ 6 if (map.containsKey(s.charAt(i))){ 7 j = Math.max(j,map.get(s.charAt(i))+1); 8 } 9 map.put(s.charAt(i),i); 10 max = Math.max(max,i-j+1); 11 } 12 return max; 13 }
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if (s==null || s.length()==0) return 0; 4 HashSet<Character> set = new HashSet<>();; 5 int l = 0, r = 0; 6 int maxLen = 0; 7 while (r < s.length()) { 8 char cur = s.charAt(r); 9 if (!set.contains(cur)) { 10 set.add(cur); 11 maxLen = Math.max(maxLen, r-l+1); 12 r++; 13 } 14 else { 15 set.remove(s.charAt(l)); 16 l++; 17 } 18 } 19 return maxLen; 20 } 21 }